I have a set of utility classes that store static const data members. Now I need to use these data members in functional classes. I am planning to use references (dont want pointers) to the static const objects, but keep getting the error below. Can you please point out the logical/technical mistake in the code?
#include <string>
class staticData
{
public:
static const int cs = 1;
static const staticData data1;
private:
staticData(int id_): _id(id_) //NOTE: Private constructer, static access only!!
{ }
int _id;
};
const staticData staticData::data1(1001);
class testReference
{
public:
testReference(): _member(staticData::data1)
{}
private:
staticData& _member;
};
invalid initialization of reference of type âstaticData&â from expression of type âconst staticDataâ
You’re attempting to reference a
constobject through a non-const reference.Thus, the original object can be modified through the reference, as the reference is non-
const, and thus you’re breaking the contract you made when declaring the object asconst.There are 2 options:
constfromstatic const staticData data1;const:const staticData& _member;EDIT:
As per your comment, you can have:
This way, you can change what
_memberpoints to (not possible with references), but you can’t change the object itself.