How can I initialize a member const reference in a derived class, when I wish to call a base class constructor?

StackOverflow https://stackoverflow.com/questions/14664390

Question

I cannot find this question even being asked anywhere...so that makes me believe i'm doing something very wrong here...

Lets say I have a base class, A, with a constructor that takes in int parameter. In my derived class, B, I wish to invoke that constructor but also initialize a member reference passed in B's constructor. How can i do this? I cannot find the syntax to add an initialization list if I call the base class constructor. Is this possible?

Lets say I have:

Class Object
{
   Object(){}
}

Class A
{
   A(int number) : m_number(number){}

public:
   int m_number;
}

Now, how would I initialize m_obj if i wish to call the non-default constructor of A?

e.g.

Class B : Class A
{
   B(int number, const Object& objRef) : A(number)
   {
       m_obj = objRef; //error, : must be initialized in constructor base/member  
                       // initializer list...but I cannot access an initializer list!!
   }

private: 
   const Object& m_obj;
}

as I said, my intent is probably all wrong here, but if it's valid, I cannot find any syntax examples on google..

go easy on me...:)

Was it helpful?

Solution

In the constructor's initialization-list:

B(int number, const Object& objRef) : A(number), m_obj(objRef)
{}

(Note, this is nothing to do with this being a subclass. You always need to use the initialization list in order to initialize a member variable that's a reference.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top