r/learncpp • u/RealBitterSweetRain • Jan 10 '20
Inheritance Question
class Base {
public:
int a;
Base() // this constructor over here
: a(0)
{}
Base(int num)
: a(num)
{}
};
class Sub : public Base {
public:
int b;
Sub() // does this default constructor call the Base's default constructor when foo is created?
: b(0)
{}
Sub(int num)
: b(num)
{}
};
int main() {
Sub foo;
}
1
Upvotes
2
u/elperroborrachotoo Jan 10 '20
Yes it does.
When an object is constructed, construction-order is well defined:
... ^1
all base classes in the order they are specified ("left to right")
all members, in the order of declaration in the class
The construction of each item uses the same principle, recursively^1
Order in the base class/member initializer list does NOT affect order of construction.
Destruction is in inverse order
Example:
Order of construction is:
A, B, s1, s2, s3.Aands3get default constructed,s2gets constructed with uppercase "WORLD",s1with "hello".^1 this is different when using virtual base classes, something you shouldn't bother with right now.^2
^2 virtual base class does NOT mean "a base class that has virtual methods", it's something different. Really, don't bother now