can there be teo destructors in c++ class code example

Example 1: destructor in c++

#include <iostream>
class Entity {
	
public:
	float x, y;
	Entity() {
		x = 0.0f;
		y = 0.0f;
      // the above is not a good practice ,instead you can use constructor member initializer list to initialize variables
		std::cout << "Created Entity" << std::endl;
		std::cout << "x " << x << " y " << y << std::endl;
		//This is a constructor and it gets called everytime we instantiate an object
		
	}
	~Entity() {
		//This is a destructor object it gets called every time object is destroyed or its scope ends
		//Note1:that this function can never return anything 
		//Note2:Followed by this ~ symbol the name of the function must be equal to class name
		std::cout << "[Destroyed Entity]" << std::endl;
	}
};

int main(){
	{
		Entity e1;
      //here constructor is called and output => Created Entity 
      //here constructor is called and output => 0,0
	}
  //here Destructor is called and output => Destroyed Entity
  // Destructor will get called here when compiler will get out of the end bracket and the lifetime of object ends
	 // have a graeater look in debug mode
	std::cin.get();
}

Example 2: test when c++ destructor is called

// order_of_destruction.cpp
#include <cstdio>

struct A1      { virtual ~A1() { printf("A1 dtor\n"); } };
struct A2 : A1 { virtual ~A2() { printf("A2 dtor\n"); } };
struct A3 : A2 { virtual ~A3() { printf("A3 dtor\n"); } };

struct B1      { ~B1() { printf("B1 dtor\n"); } };
struct B2 : B1 { ~B2() { printf("B2 dtor\n"); } };
struct B3 : B2 { ~B3() { printf("B3 dtor\n"); } };

int main() {
   A1 * a = new A3;
   delete a;
   printf("\n");

   B1 * b = new B3;
   delete b;
   printf("\n");

   B3 * b2 = new B3;
   delete b2;
}

Output: A3 dtor
A2 dtor
A1 dtor

B1 dtor

B3 dtor
B2 dtor
B1 dtor

Tags:

Cpp Example