CPP Constructor Calling Sequence

What about Constructors and Destructors calling sequence?

  • For each created object of a class, the system calls Constructer and just before the object is deleted and fall out of scope the system calls the destructor.
  • When a class is derived by another class this Constructors and Destructors calling sequence will be for the example above as:
    1. Person constructor ...
    2. Employee constructor ...
    3. Employee destructor ...
    4. Person destructor ...
  • Remember that a drived class must call the right base class constructor if it is not using the default base constructor. (see example belove)
    Example of Constructor and destructor calling sequence in an inheritence relationship:
    #include <iostream>
    #include <cstring>
    
    class Person {
    public:
      Person (int age, int weight){
        std::cout << "Person constructor ...\n";
        this->age = age;
        this->weight = weight;
      }
      ~Person() {
        std::cout << "Person destructor ...\n";
      }
      int getAge() { return age; }
      int getWeight() { return weight; }
    protected:
      int age;
    private:
      int weight;
    };
    
    class Employee : public Person {
    public:
      Employee (int age, int weight, int salary): Person(age,weight){
        std::cout << "Employee constructor ...\n";
        this->salary = salary;
      }
      ~Employee() {
        std::cout << "Employee destructor ...\n";
      }
       int getSalary() { return salary; }
    private:
      int salary;
    };
    int main(int argc, char **argv) {
      Person * pRicard = new Person(40, 70);
      delete pRicard;
      std::cout << "\n";
      Employee * pObama = new Employee(45, 65, 50000);
      delete pObama;
      std::cout << "\n";
      return 0;
    }
    When we run this application, the result will be:
    Person constructor ...
    Person destructor ...
    
    Person constructor ...
    Employee constructor ...
    Employee destructor ...
    Person destructor ...

    You can download this example here (needed tools can be found in the right menu on this page).

© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.