Reputation: 160
#include <iostream>
using namespace std;
struct A {
A() { cout << "A "; }
};
struct B: A {
B() { cout << "B "; }
};
struct C: A {
C() { cout << "C "; }
};
struct D: C, B {
D() { cout << "D "; }
};
int main(){
D d;
}
The result is A C A B D. My understanding is that D inherits from C and B, and if an object "d" is created in D, then it also has the attributes from C and B. And since B and C both inherits from A, D should also inherit from A. Can someone explain the result please? My prediction is way off...
Upvotes: 1
Views: 66
Reputation:
The base constructor(s) are called first, then the main constructor.
D()
=> C() then B() then D
=> A() C then A() B then D
=> A C then A B then D
=> A C A B D
Order of execution in constructor initialization list
Upvotes: 1
Reputation: 10725
Inheritance reflects an IS A relationship.
A D object is a C and a B. A C is in turn an A. Therefore, to create an instance of D, the runtime has to first create an A and then a C. That explains the first two characters of the output. Continue with this reasoning and you'll get the rest.
Upvotes: 0