Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++populating base class protected member using derived class constructor

I have something like this:

Class Base
{
  public:
    Base();
  protected:
    someType myObject;
}

Class Child:public someNamespace::Base
{
   //constructor
   Child(someType x):myObject(x){}
}

Class Child, and Base are in 2 different namespaces... Compiler complains that my Child class does not have a field called myObject

Anyone know why? Is it because its illegal to populate a Base member from a Child constructor?

Thanks

like image 634
Telenoobies Avatar asked Nov 28 '25 10:11

Telenoobies


2 Answers

You cannot initialize the inherited member like that. Instead, you can give the base class a constructor to initialize that member, then the derived class can call that constructor.

class Base
{
  public:
    Base(someType x) : myObject{x} {}
  protected:
    someType myObject;
}

class Child : public Base
{
  public:
    //constructor
    Child(someType x) : Base(x) {}
}

In general, a class should be responsible for initializing its own members.

like image 192
Cory Kramer Avatar answered Nov 30 '25 01:11

Cory Kramer


The problem here is that you are initializing your inherited myObject in the initialization list. When an object of the derived class is created, before entering the body of the constructor of the derived class the constructor of the base class is called (by default, if base class has default or no parameter constructor, otherwise you have to explicitly call the constructor in the initialization list).

So, when you do :: Class Child:public someNamespace::Base your constructor for the base class has not yet been called, which is why your compiler complains :: Child class does not have a field called myObject, that is you are actually trying to assign a value to something which has not yet been declared and defined! It will get defined after the constructor the Base class enters its execution.

So, your Child class constructor will look something like this ::

   Child(someType x) {
      myObject = x;
   }

Working ideone link :: http://ideone.com/70kcdC

I found this point missing in the answer above, so I thought it might actually help!

like image 43
user007 Avatar answered Nov 30 '25 00:11

user007