I having hard time in solving those kind of question. In an exam I going to take in a few days, they show a program in C++ which has Multiple Inheritance:
struct X {
X(){cout << "X" << endl;}
};
struct A : virtual X {
int i;
A(){cout << "A" << endl;}
};
struct B : A {
int i;
B(){cout << "B" << endl;}
virtual void f() {cout << "f" << endl;}
};
struct C : A {
int i;
C(){cout << "C" << endl;}
C(int i){cout << "C2" << endl;}
virtual void g() {cout << "g" << endl;}
};
struct D : virtual B, virtual C {
int i;
D( int i) : C(i), B() {cout << "D" << endl;}
};
And show some code from main:
D* d = new D(2014);
C* c = d;
B* b = d;
And than ask "what will be the output?" I don't need the solution, I can always
just run or debug it but I need to understand the intuition because I will not have the debugger with me on the exam. Now I know the algorithm I need to follow:
5 Initialization shall proceed in the following order:
— First, and only for the constructor of the most derived class as
described below, virtual base classes shall be initialized in the
order they appear on a depth-first left-to-right traversal of the
directed acyclic graph of base classes, where “left-to-right” is the
order of appearance of the base class names in the derived class
base-specifier-list.
— Then, direct base classes shall be initialized in declaration order
as they appear in the base-specifier-list (regardless of the order of
the mem-initializers).
— Then, nonstatic data members shall be initialized in the order they
were declared in the class definition (again regardless of the order
of the mem-initializers).
— Finally, the body of the constructor is executed. [Note: the
declaration order is mandated to ensure that base and member
subobjects are destroyed in the reverse order of initialization. ]
But I really having bad time solving them, it does not make any sense. Is it possible to show the intuition, maybe a trick or tip on solving those kind of questions? Maybe to show dark corners? Maybe somehow to write down all the classes/structs, write the vbase classes somehow in order to easy see to output?
Related
In my code, I have a basic diamond pattern:
CommonBase
/ \
/ \
DerivedA DerivedB
\ /
\ /
Joined
It's implemented like this, with the common base class having a default constructor and a constructor taking a parameter:
struct CommonBase {
CommonBase() : CommonBase(0) {}
CommonBase(int val) : value(val) {}
const int value;
};
struct DerivedA : public virtual CommonBase {
void printValue() {
std::cout << "The value is " << value << "\n";
}
};
struct DerivedB : public virtual CommonBase {
void printValueTimes2() {
std::cout << "value * 2 is " << value * 2 << "\n";
}
};
struct Joined : public DerivedA,
public DerivedB {
Joined(int val) : CommonBase(val) {
std::cout << "Constructor value is " << val << "\n";
std::cout << "Actual value is " << value << "\n";
}
};
The Joined class initializes the virtual base using the constructor that takes a parameter, and everything works as expected.
However, when I derive a class from the Joined class, something strange happens - the CommonBase's default constructor is called unless I explicitly initialize CommonBase in the derived classes constructor as well.
This is demonstrated using this code:
struct JoinedDerivedA : public Joined {
JoinedDerivedA() : Joined(99) {
printValue();
}
};
struct JoinedDerivedB : public Joined {
JoinedDerivedB() : Joined(99), CommonBase(99) {
printValue();
}
};
int main() {
std::cout << "======= Joined =======\n";
Joined j(99);
j.printValue();
std::cout << "\n=== JoinedDerivedA ===\n";
JoinedDerivedA a;
std::cout << "\n=== JoinedDerivedB ===\n";
JoinedDerivedB b;
return 0;
}
The output of this code is
======= Joined =======
Constructor value is 99
Actual value is 99
The value is 99
=== JoinedDerivedA ===
Constructor value is 99
Actual value is 0 // <-- unexpected behaviour
The value is 0
=== JoinedDerivedB ===
Constructor value is 99
Actual value is 99
The value is 99
Why is this the case? Is it possible to not have to explicitly initialize the common base class in derived classes again?
Here's the code on ideone, so you can run it yourself: https://ideone.com/Ie94kb
This is specified in Initializing bases and members [class.base.init] (12.6.2 in draft n4567). We can read in §13 (emphasize mine):
(13) In a non-delegating constructor, initialization proceeds in the following order:
(13.1) — First, and only for the constructor of the most derived class (1.8), virtual base classes are initialized in
the order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes,
where “left-to-right” is the order of appearance of the base classes in the derived class base-specifier-list.
(13.2) — Then, direct base classes are initialized in declaration order as they appear in the base-specifier-list
(regardless of the order of the mem-initializers).
(13.3) — Then, non-static data members are initialized in the order they were declared in the class definition
(again regardless of the order of the mem-initializers).
(13.4) — Finally, the compound-statement of the constructor body is executed.
[ Note: The declaration order is mandated to ensure that base and member subobjects are destroyed in the
reverse order of initialization. —end note ]
That means that the virtual base class will be initialized before the initialization of Joined. So in DerivedJoinedA, it is default initialized with a value of 0. Then when initializing Joined, the initialization of CommonBase is ignored because it has already been initialized and value keeps its 0 value.
That is the reason why you have to initialize the virtual base classes in the most derived class.
This question already has answers here:
Are parent class constructors called before initializing variables?
(7 answers)
Closed 7 years ago.
I have the following code:
class A{
public:
A(int* i){
std::cout << "in A()" << i << std::endl;
}
};
class B: public A{
public:
B(): i{new int{10}}, A{i}{
std::cout << "in B()" << std::endl;
}
private:
int* i;
};
int main()
{
B b;
}
In A constructor I have 0 (which is expected). But I want to initialize i before. Is it possible at all?
i is a data member of class B, so in order to be created, an object of class B has to be created first. So the answer, is no.
No, it is not possible since the base class initialization is always prior to derived class initialization.
C++11, 12.6.2
10 In a non-delegating constructor, initialization proceeds in the following order:
First, and only for the constructor of the most derived class (1.8), virtual base classes are initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes, where "left-to-right" is the order of appearance of the base classes in the derived class base-specifier-list.
Then, direct base classes are initialized in declaration order as they appear in the base-specifier-list (regardless of the order of the mem-initializers).
Then, non-static data members are initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).
Finally, the compound-statement of the constructor body is executed.
Initialize member before base constructor. Possible?
No, that is not possible. The standard mandates that the base classes be initialized first before the members of the class are initialized.
B(): i{new int{10}}, A{i}{
std::cout << "in B()" << std::endl;
}
is transformed to:
B(): A{i}, i{new int{10}}{
std::cout << "in B()" << std::endl;
}
I am studying for my final exam. I stumbled upon this question from previous years and I can't seem to fully understand whats happening.
Given this code, determine the output
#include <iostream>
using namespace std;
struct A {
A(int a): _a(a) {cout << "A::A, a=" << _a << endl;}
~A() { cout << "A::~" << endl; }
int _a;
};
struct B: public A
{
B(int b):A(b) { cout << "B::B" << endl; }
~B() { cout << "B::~" << endl; }
};
struct C: public B
{
A a;
B b;
C(int a=10, int b=20):a(a), b(a*b), B(b) {}
~C() { cout << "C::~" << endl; }
};
int main() {
C allTogetherNow;
return 0;
}
I tried to compile the code and I was given a warning:
warning: field 'b' will be initialized after base 'B'
[-Wreorder] C(int a=10, int b=20):a(a), b(a*b), B(b) {} ~C() { cout << "C::~" << endl; }
^ 1 warning generated.
and the following output:
A::A, a=20
B::B
A::A, a=10
A::A, a=200
B::B
C::~
B::~
A::~
A::~
B::~
A::~
The destruction order is kind of clear (last constructed - first destructed), but I can't seem to get ahold of the construction order/pattern.. What am I missing? A clarification of the Warning I received would be extra helpful. Also, if you could refer me to extra reading material on this particular subject.
Thank you.
The initialization order is precisely defined in the standard:
12.6.2./10: In a non-delegating constructor, initialization proceeds in the following order:
— First, and only for the constructor
of the most derived class (1.8), virtual base classes are
initialized in the order they appear on a depth-first left-to-right
traversal of the directed acyclic graph of base classes, where
“left-to-right” is the order of appearance of the base classes in the
derived class base-specifier-list.
— Then, direct base classes are
initialized in declaration order as they appear in the
base-specifier-list (regardless of the order of the mem-initializers).
— Then, non-static data members are initialized in the order they
were declared in the class definition (again regardless of the order
of the mem-initializers).
— Finally, the compound-statement of the
constructor body is executed.
So when you intialize C, its base class is first initialised, i.e. B with default 20 which itself requires A to be initialised first with 20. Only then is initialisation of B completed.
Then, A and B being intialized, the members of C are initalized, starting first with a with the default parameter 10, then with b(200). As b is a B, it will first require the initializeation of its own base A. Then initialisation of of b can be completed. And finally the initialisation of C is completed.
By the way, it's not part of the question but remember for your exam:
12.4/7: Bases and members are destroyed in the reverse order of the completion of their constructor.
Note about the warning:
My compiler doesn't generate this warning. There is no reason for it, as the mem-initilizer B(b) clearly uses the parameter b of your consturctor. It's only an hypotheses, but I suspect your compiler raise a false positive because b is also the name of a member (which would indeed not be initialised when calling the base). If I'm right, the following change should not raise a warning anymore:
C(int a=10, int bbb=20):a(a), b(a*bbb), B(bbb) { cout << "C::C" << endl;}
This line:
C(int a=10, int b=20):a(a), b(a*b), B(b) {}
Should be:
C(int a=10, int b=20): B(b), a(a), b(a*b) {}
In C++, the initialization order is fixed. For your type C, it will always be:
Base Class B
Member variable A a;
Member variable B b;
In your initializer list you ordered it differently. And so your compiler warned you in case you expected the initializer list's order to matter.
How the compiler do composition in inheritance?
suppose that I create an object of a derived class where both the base class and the derived class contain via composition object of other classes. I want some example to explain constructors and destructors.
I'm not going to make this overly easy for you, given it does indeed look like homework. If you can think through and understand what's below - good luck to you....
The base class's constructor is invoked, which will - for each member variable in order of declaration in the base class - call either the constructor corresponding to arguments specified in the base class initialisation list or the default constructor if any (otherwise the member's left uninitialised, though sometimes e.g. earlier zero-initalisation of the memory the object is contained in - perhaps due to new (p) T() notation or being static - will guarantee specific values anyway). Then, the derived constructor does the same for its own data members. Destruction happens in reverse order.
If you need to demonstrate the basic principles, you could use some variants of:
struct M { // Marker
int id;
M(int i) : id(i) { cout << "\tconstruction M" <<id<< endl; }
~M() { cout << "\tdestruction M" <<id<< endl; }
};
struct B { //Base
M mb;
B() : mb(1) { cout << "construction B (body finished)" << endl; }
~B() { cout << "destruction B (body finished)" << endl; }
};
struct D : public B { //Derived
M md;
D() : md(2) { cout << "construction D (body finished)" << endl; }
~D() { cout << "destruction D (body finished)" << endl; }
};
Of course, it's simplified, but it shows that the base is constructed before the derived, and members are constructed before constructore body is executed. It shows as well as that destruction is performed in reverse order of construction.
But that's only the most obvious. You should aslo show examples demonstrating in which order members are constructed when there are severals, and what happens in multiple inheritance, as well as the case of static members.
#include <iostream>
using namespace std;
struct A{
A() {cout << "A" << endl;}
A(int a) {cout << "A+" << endl;}
};
struct B : virtual A{
B() : A(1) {cout << "B" << endl;}
};
struct C : virtual A{
C() : A(1) {cout << "C" << endl;}
};
struct D : virtual A{
D() : A() {cout << "D" << endl;}
};
struct E : B, virtual C, D{
E(){cout << "E" << endl;}
};
struct F : D, virtual C{
F(){cout << "F" << endl;}
};
struct G : E, F{
G() {cout << "G" << endl;}
};
int main(){
G g;
return 0;
}
Program prints:
A
C
B
D
E
D
F
G
I would like to know what rules should I use to determine in what order constructors get called. Thanks.
You should follow the rules given in the C++ standard:
[C++11: 12.6.2/10]: In a non-delegating constructor, initialization proceeds in the following order:
First, and only for the constructor of the most derived class (1.8), virtual base classes are initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes, where “left-to-right” is the order of appearance of the base classes in the derived class base-specifier-list.
Then, direct base classes are initialized in declaration order as they appear in the base-specifier-list (regardless of the order of the mem-initializers).
Then, non-static data members are initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).
Finally, the compound-statement of the constructor body is executed.
[ Note: The declaration order is mandated to ensure that base and member subobjects are destroyed in the reverse order of initialization. —end note ]
Virtual base subobjects are constructed first, by the most-derived class, before any other bases. This is the only way that makes sense, since the relation of the virtual bases to tbe most-derived object is not known until object construction, at runtime (hence "virtual"). All intermediate initializers for virtual bases are ignored.
So, what are your virtual bases? G derives from E and F. E derives virtually from C, which in turn derives virtually from A, so A, C are first. Next, F doesn't add any further virtual bases. Next, E has non-virtual bases B and D, in that order, which are constructed next, and then E is complete. Then comes F's non-virtual base D, and F is complete. Finally, G is complete.
All in all, it's virtual bases A, C, then non-virtual bases B, D, E and D, F, and then G itself.
You can investigate the order of constructor calls from this quote of the C++ Standard and try to trap it yourself
10 In a non-delegating constructor, initialization proceeds in the
following order: — First, and only for the constructor of the most
derived class (1.8), virtual base classes are initialized in the order
they appear on a depth-first left-to-right traversal of the directed
acyclic graph of base classes, where “left-to-right” is the order of
appearance of the base classes in the derived class
base-specifier-list. — Then, direct base classes are initialized in
declaration order as they appear in the base-specifier-list
(regardless of the order of the mem-initializers). — Then, non-static
data members are initialized in the order they were declared in the
class definition (again regardless of the order of the
mem-initializers). — Finally, the compound-statement of the
constructor body is executed. [ Note: The declaration order is
mandated to ensure that base and member subobjects are destroyed in
the reverse order of initialization. —end note ]