You do this in the member initializer-list of the constructor of the subclass. Because parent
is not a direct base of child2
. You have to give a constructor for your direct bases (child
) to child2
and may be in contructor of child1
, you can initialize your base class parent
.
Thereby, you will have to propagate initialization in a base class all way through the hierarchy but could directly address the "very base" constructor (parent
) in member initializer list of child2
.
Try this:
class parents {
int x;
public:
parents(int a)
{
x = a;
}
};
class child1: public parents {
int y;
public:
child1(int b): parents(b)
{
y = b;
}
};
class child2: public child1{
int z;
public:
child2(int c): child1(c)
{
z = c;
}
};
Or
You can use virutal
inheritance. Virtual bases are the exception to the above statement.
They are always initialized in leaf classes, otherwise potentially you get multiple constructor calls for the same base. So if you make base virtual, not only can you initialize it in child2
, you must.
Furthermore, you will actually be enforced to call it in any "Grandchild"-class, so you can't forget it by accident:
class parents {
int x;
public:
parents(int a)
{
x = a;
}
};
class child1: public virtual parents {
int y;
public:
child1(int b): parents(b)
{
y = b;
}
};
class child2: public virtual child1{
int z;
public:
child2(int c): child1(0), parents(1)
{
z = c;
}
};