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

Xiith is created for educational, experimental, and schooling purpose. Examples on Xiith are made easier to make a better or basic understanding. Tutorials, testimonials, and examples are continuously checked to avoid delusion, but we cannot take complete responsibility of all programs on Xiith. When you are operating this site, you have to agree to read and accept our terms of use, cookie and privacy policy.Copyright © 2020 by Xiith. All Rights Reserved. About us.