Reputation: 31
I am trying to understand the order of exectution of a class which has nested objects of another class inside it. Here's my simple program :
#include<iostream>
#include <string>
using namespace std;
class Alpha
{
int a;
public:
Alpha(int x)
{
a=x;
}
};
class Beta
{ int b;
public:
Beta(int y)
{
b=y;
}
};
class Gamma
{
Alpha A;
Beta B;
int c;
public:
Gamma(int a,int b, int d): A(a), B(b)
{
c=d;
}
};
void main()
{
Gamma g(5,6,7);
}
As you can see, Gamma has 2 nested objects. Now when the first line of main() is executed, how does the execution start inside the class Gamma? The constructer is called first or the objects/data-members are created first?
Upvotes: 3
Views: 63
Reputation: 1
The constructer is called first or the objects/data-members are created first?
From an initializer list the members or base class constructor calls are executed before the constructors body of the containing / inherited class.
You can easily check what's going on placing some output statements in the constructors
Alpha(int x) {
cout << "a = " << a << std::endl;
a=x;
cout << "Alpha(" << a << ")" << std::endl;
}
Beta(int y) {
cout << "b = " << b << std::endl;
b=y;
cout << "Beta(" << b << ")" << std::endl;
}
Gamma(int a,int b, int d): A(a), B(b) {
cout << "c = " << c << std::endl;
c=d;
cout << "Gamma(" << c << ")" << std::endl;
}
Output is
a = 0
Alpha(5)
b = 134514731
Beta(6)
c = -1218371596
Gamma(7)
See here for a fully working sample.
Upvotes: 1
Reputation: 726849
The question of constructor execution order is simple: first, Gamma
constructor starts, but then it immediately proceeds to initializing Alpha
and Beta
, as specified in your initialier list. Once the intializer list is done, the body of Gamma
's constructor is executed.
There is an important twist to this: C++ will initialize nested objects in the order in which they are declared in the class, not in the order in which they are listed in the initializer list. In other words, Alpha
will be initialized ahead of Beta
even if you reverse A(a)
and B(b)
:
// The compiler will issue a warning for this
Gamma(int a,int b, int d): B(b), A(a)
{
c=d;
}
Upvotes: 3
Reputation: 206697
Objects in the initialization list are initialized first. Then, the body of the constructor inside {}
is executed.
Upvotes: 0