Telenoobies
Telenoobies

Reputation: 936

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

Upvotes: 3

Views: 1073

Answers (2)

user007
user007

Reputation: 2172

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!

Upvotes: 2

Cory Kramer
Cory Kramer

Reputation: 117876

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.

Upvotes: 4

Related Questions