Monday, 18 July 2016

How order of object construction is decided when more than one class object is kept as member of the class?

 
#include<iostream>
class Comment
{
public:
Comment(int a)
{
       std::cout<<"Comment constructor called"<<std::endl;
}
};

class Bugs
{
public:
Bugs(double a)
{
       std::cout<<"Bugs constructor called"<<std::endl;
}
};


class Post
{

public:
Post(): c(35), b(25.25)
{
      
       std::cout<<"Post constructor called"<<std::endl;
}
private:
Bugs b;
Comment c;
};

int main()
{
Post p;
return 0;
}

OUTPUT:


Bugs constructor called
Comment constructor called
Post constructor called

EXPLANATION:

The order of construction of objects is decided based on the order of declaration in the class. It is not decided based on the way we call the objects constructor in the initialization list.

Here b is declared first in the class, so bugs constructor is called even though comment is first initialized in the post constructor.