Constructors set up objects when they are created. Knowing the order helps you understand how parts of a program start working together.
0
0
Constructor calling order in C++
Introduction
When you have a class that inherits from another class and want to know which constructor runs first.
When your class has member objects and you want to understand the order they get initialized.
When debugging object creation to find out why some parts are not ready yet.
When designing classes with multiple layers and you want to control setup steps.
Syntax
C++
class Base { public: Base() { /* base constructor code */ } }; class Derived : public Base { public: Derived() { /* derived constructor code */ } };
The base class constructor runs before the derived class constructor.
Member objects are constructed before the body of the constructor runs, in the order they are declared.
Examples
This shows the base constructor runs first, then the derived constructor.
C++
class Base { public: Base() { std::cout << "Base constructor\n"; } }; class Derived : public Base { public: Derived() { std::cout << "Derived constructor\n"; } }; int main() { Derived d; return 0; }
Member objects m1 and m2 are constructed before the Container constructor runs, in the order they are declared.
C++
class Member { public: Member() { std::cout << "Member constructor\n"; } }; class Container { Member m1; Member m2; public: Container() { std::cout << "Container constructor\n"; } }; int main() { Container c; return 0; }
Sample Program
This program shows the order of constructor calls: first the base class, then member objects in order, then the derived class.
C++
#include <iostream> class Base { public: Base() { std::cout << "Base constructor\n"; } }; class Member { public: Member() { std::cout << "Member constructor\n"; } }; class Derived : public Base { Member m1; Member m2; public: Derived() { std::cout << "Derived constructor\n"; } }; int main() { Derived d; return 0; }
OutputSuccess
Important Notes
Base class constructors always run before derived class constructors.
Member objects are constructed in the order they are declared, not the order in the constructor initializer list.
Destructor calls happen in the reverse order of constructors.
Summary
Base class constructor runs first.
Member objects are constructed next, in declaration order.
Derived class constructor runs last.