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
	Country();  //This is the constructor
	~Country();  //This is the destructor

	cout << "This is Taylor Swift Singing.";
	cout << endl;

	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.


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