I am trying to initialize a reference object through the initialization list in the class constructor and I would need your inputs on why I am not able to initialize it in the following way. Am I not allowed to initialize a reference in the following way?
class ObjectA
{
private:
char* _nameA;
int _velocityA;
public:
ObjectA(char* name, int velocity)
{
name = name;
_velocityA = velocity;
}
};
I get an error in the following initialization list which says a reference of type “ObjectA &” (not const-qualified) cannot be initialized with a value of type “char *” Why exactly am I getting this error? and what am I doing wrong?
class ObjectB
{
private:
ObjectA& objA;
public:
ObjectB(char* engName, int _velocityA):objA(engName, _velocityA)
{
}
};
The problem is you tried to initialize the reference
objAin the same way you create an object.Remember
objAis a reference, not a pointer or a variable so thatobjA(engName, _velocityA)would call the constructor ofObjectA.The constructor of
ObjectBshould take anObjectAobject as parameter, so that the referenceobjAcan refer.