Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working of nested class objects?

Tags:

c++

object

oop

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?

like image 997
user3693825 Avatar asked Apr 18 '26 18:04

user3693825


1 Answers

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;
}
like image 88
Sergey Kalinichenko Avatar answered Apr 20 '26 08:04

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!