Constructor and Destructor

The execution order of constructor and destructor!

class Base {
  public:
  Base ( ) {
    cout << "Inside Base constructor" << endl;
  } 

  ~Base ( ) {
    cout << "Inside Base destructor" << endl;
  }
};

class Derived : public Base {
  public:
  Derived  ( ){
    cout << "Inside Derived constructor" << endl;
  } 
  ~Derived ( ){
    cout << "Inside Derived destructor" << endl;
  }
};

int main( )
{
  Derived *x = Derived();
  delete x;
  Base *y = Derived();
  delete y;
  return 0;
}

Base class constructors and derived class destructors are called first

So the output of the code above would look like:

Inside Base constructor
Inside Derived constructor
Inside Derived destructor
Inside Base destructor
Inside Base constructor
Inside Derived constructor
Inside Base destructor
  • When deleting the base class pointer the destructor for the "Derive" class does not get called. (Not a problem when deleting the derived class pointer.)
  • Fix it: make the base class destructor virtual. It ensures that the destructor for any class that derives from Base will be called.

Syntax

class Rectangle {
  private:
    int width, height;
  public:
    Rectangle(): width(0), height(0) {}
    Rectangle(int w, int h ): width(w), height(h) {}
    void set_values (int w, int h) {
      width = w;
      height = h;
    }
    int area () {return width*height;}
};

results matching ""

    No results matching ""