destructor c++ why 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: destructor in c++

#include <iostream>
using namespace std;
class HelloWorld{
public:
  //Constructor
  HelloWorld(){
    cout<<"Constructor is called"<<endl;
  }
  //Destructor
  ~HelloWorld(){
    cout<<"Destructor is called"<<endl;
   }
   //Member function
   void display(){
     cout<<"Hello World!"<<endl;
   }
};
int main(){
   //Object created
   HelloWorld obj;
   //Member function called
   obj.display();
   return 0;
}

Tags:

Cpp Example