I have the following problem at hand. There is a class, Foo and another one called Bar which is a member of class Foo.
class Bar{
private:
some stuff;
public:
Bar();
some other_stuff;
};
class Foo{
private:
Bar bar;
public:
Foo(); // Initialize the bar object here in the constructor
void doSomethingWithBar();
};
Now both classes are huge! For some application, I need to make changes to both Foo and Bar and so there are Foo_Derived and Bar_Derived classes.
class Bar_Derived: public Bar{
private:
some NEW_stuff;
public:
Bar_Derived();
some New_other_stuff;
};
class Foo_Derived: public Foo{
private:
Bar_Derived bar;
public:
Foo_Derived();
void doSomethingWithBar();
};
As far as I understand inheritance, once Foo_Derived() is called, the base class constructor for Foo is also called which initializes the bar object in the base class (of type Bar. What should I do so that the bar object in the derived class is used instead? (of type Bar_Derived). I only need the base class (Foo) to initialize the base part of the bar object and do the rest in the Foo_Derived class myself. Is this even possible?
Sorry if the question is not clear. I’m just really confused myself!
The base class initializer only does initialize the base part of the object, since that’s all it knows about. A class initializer should only initialize those things that always need to be initialized for all members of that class.
In the constructor for
Foo_Derived, you can use an initializer list to specify whichBar_Derivedconstructor to invoke. TheBar_Derivedconstructor can use anyBarconstructor it wishes. If you don’t have aBar_Derivedconstructor that constructsFoo_Derived::barthe way you want it, you should write one or rethink how you have your hierarchy set up.