1
#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...

noobcoder
  • 150
  • 2
  • 16
  • 1
    Hi. Welcome to SO. You should add a tag for the programming language so that the question shows up for people who are experts at that language. :) – Simba Dec 29 '16 at 13:06
  • Hi! Thanks for the tip! I'm still new to SO ^^ – noobcoder Dec 29 '16 at 13:10
  • @codenoob Welcome to Stack Overflow. Please take the time to read [The Tour](http://stackoverflow.com/tour) and refer to the material from the [Help Center](http://stackoverflow.com/help/asking) what and how you can ask here. – πάντα ῥεῖ Dec 29 '16 at 13:37

2 Answers2

1

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

Community
  • 1
  • 1
0

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.

Andres
  • 10,561
  • 4
  • 45
  • 63