C++ Program using virtual constructor and destructor


In this program, You will learn how to implement a virtual constructor and destructor in C++.


Test() { } 
||
 ~Test () { } 
|| 
virtual void draw() = 0;

Example: How to implement a virtual constructor and destructor in C++.

#include<iostream>
using namespace std;

class Shape {

public:
  Shape() {
      cout << "shape - constructor\n";
  }

  ~Shape() {
      cout << "shape - destructor\n";
  }

  virtual void draw() = 0;
};

class Rectangle : public Shape {
public:

  Rectangle() {
      cout << "rectangle constructor\n";
  }

  ~Rectangle() {
      cout << "rectangle destructor\n";
  }

  void draw() {
      cout << "rectangle\n";
  }
};

class Circle : public Shape {

public:
  Circle() {
      cout << "circle constructor\n";
  }

  ~Circle() {
      cout << "circle destructor\n";
  }

  void draw() {
      cout << "circle\n";
  }
};

int main() {

  Shape* bptr;
  bptr = new Rectangle();

  bptr->draw();
  delete bptr;
  cout << "\n";

  bptr = new Circle();
  bptr->draw();
  delete bptr;

  return 0;
}

Output:

shape - constructor
rectangle constructor
rectangle
shape - destructor

shape - constructor
circle constructor
circle
shape - destructor