Menu
C++ Tutorials

C++

Destructors



Tutorials > C++ > Destructors

View Full Source

Introduction

In the last tutorial, we covered constructors. This tutorial will cover the other end of the scale, destructors. They work in the same way as constructors except that the destructor is called when an object is destroyed or moves out of scope. Another difference is that there can only be one destructor. A destructor is declared as follows :

~class_name();

A destructor is very useful when memory needs to be freed up or if some action needs to be taken when an object is destroyed.

Contents of main.cpp :


#include <iostream>
#include <stdlib.h>

using namespace std;

class Player
{
public :

	Player();

Below, we declare the Player destructor.

	~Player();

	int health;
	int mana;

The inventory pointer below will be used to point to an array of inventory items.

	char **inventory;

	void attack()
	{ cout << "Player Attacks" << endl; }
};

The constructor initializes the health and mana variables and allocates memory for 10 character pointers.

Player::Player() : health(100), mana(50)
{
	inventory = new char*[10];
	cout << "Player Created" << endl;
}

The destructor's body is given below. The memory allocated to the inventory variables is now freed up.

Player::~Player()
{
	delete[] inventory;
	cout << "Player Destroyed" << endl;
}

When the code below runs, take note of the messages that are printed out. When the object is removed from scope, the "Player Destroyed" message is displayed.

int main()
{
	{
		Player grant;
		grant.attack();
	}

	system("pause");

	return 0;
}

With the knowledge of both constructors and destructors, you are now able to efficiently initialize and destroy objects that you create.

Please let me know of any comments you may have : Contact Me

Source Files : Visual Studio Dev-C++ Unix / Linux

< Tutorial 47 - Constructors Tutorial 49 - Access Specifiers >

Back to Top


All Rights Reserved, © Zeus Communication, Multimedia & Development 2004-2005

Read the Disclaimer

Links