Home | | Computer Science 11th std | C++: Order of constructor invocation

Example Program in C++ - C++: Order of constructor invocation | 11th Computer Science : Chapter 14 : Classes and objects

Chapter: 11th Computer Science : Chapter 14 : Classes and objects

C++: Order of constructor invocation

The constructors are executed in the order of the object declared.

Order of constructor invocation

 

The constructors are executed in the order of the object declared. (If it is in same statement left to right)

For example

Test t1;

Test t2; // the order of constructor execution is first for t1 and then for t2.

Let us consider the following example

Sample s1,s2,s3 ;                    //The order of construction is s1 then s2 and finally s3

But if a class containing an object of another class as its member then that class constructor is executed first.

 

Illustration14.27 to illustrate order of execution of constructor

#include<iostream>

using namespace std;

class outer

{

      int data;

      public:

      outer()

      {

      cout<<"\nconstructor of class outer ";

      }

};

class inner

{

      outer ot;                 // object ot of class outer is declared in class inner

      public:

      inner()

      {

      cout<<"\n constructor of class inner ";}

};

int main()

{

      inner in;

      return 0;

}

Output:

constructor of class outer

constructor of class inner

 

Tags : Example Program in C++ , 11th Computer Science : Chapter 14 : Classes and objects
Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
11th Computer Science : Chapter 14 : Classes and objects : C++: Order of constructor invocation | Example Program in C++

Related Topics

11th Computer Science : Chapter 14 : Classes and objects


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2024 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.