简体   繁体   中英

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

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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM