C++: A simple experiment on Constructor/Destructor

This entry is part 25 of 61 in the series C++

We can work out a simple example to show how a constructor and desctructor work.

Destructors destroy the class objects created by constructors. The destructors have the same name as their class, preceded by a tilde (~).

This example does nothing but create the ts instance or object and once the program exits out of the main, the desctructor will be called releasing the ts instance back to the memory.

#include <iostream>
#include <string>

using namespace std;

class Country
{
public:
	Country();  //This is the constructor
	~Country();  //This is the destructor
};

Country::Country()
{
	cout << "This is Taylor Swift Singing.";
	cout << endl;
}

Country::~Country()
{
	cout << "This is Taylor Swift Signing Off.";
	cout << endl;
}

int main()
{
	Country ts; // instance declaration
	return 0;
}

When the ts instance declaration is called in line 27, the constructor function will be called automatically.

destructor

Series Navigation<< C++: The actual constructor
C++: Constructor with parameters >>

Leave a comment

Leave a Reply