C++ Classes – Constructors and destructors

In the last C++ tutorial we looked at the basic concept of classes. In this C++ programming tutorial we take another look at classes.

Constructor and Destructor

Classes can have complicated internal structures, so object initialization and clean-up of a class is much more complicated then for any other data structures. Constructors and destructors are special member functions of classes that are used to construct and destroy class objects. The construction can be for example: initialization for objects or memory allocation. The destruction may involve de-allocation of memory or other clean-up for objects.

Constructors and destructor’s are declared within a class declaration (as like any other member function). A constructor or a destructor can be defined in-line or external to the class declaration. We may declare some default arguments when we make a constructor. There are some restrictions that apply to constructors and destructors:

  • Constructors and destructors cannot have a return type (not even void).
  • Pointers and references cannot be used on constructors and destructor’s (It is not possible to get there address)
  • Constructors and destructor’s cannot be declared static, const or volatile.
  • Constructors cannot be declared with the keyword virtual.

Note: the same access rules apply to constructors and destructors as with any other member function.

Constructors are called automatically by the compiler when defining class objects. The destructor’s are called when a class object goes out of scope.

So let’s take a look at an example:


	#include<iostream>
	using namespace std;

	class CAdd
	{

	public:
		int one;

		CAdd(int two)
		{
			cout << "A constructor is called" << endl;
			one=two;
		}

		CAdd()
		{
			cout << "A default constructor is called " << endl;
		}

		~CAdd()
		{
			cout << "Destructing " << one << endl;
		}

		int add()
		{
			return(one+one);
		}
	};

	int main()
	{
		CAdd myobj1(4);
		CAdd myobj2;

		cout << myobj1.one << endl;
		cout << "Enter a number : " ;

		cin >> myobj2.one;
		cout << myobj2.add() << endl;

		return(0);
	}

Note: with CAdd myobj2; we did not use any parentheses because we want to call the default constructor. Putting the parentheses behind myobj2 will result in an error.

The statement :


	CAdd(int two)
	{
		cout << "A constructor is called" << endl;
		one=two;
	}

declares the constructor of the class CAdd. The name of the constructor is the same as the name of the class. If statement CAdd myobject(4) is called this constructor is called (because of the number between the parentheses in myobject(). (The compiler will call the constructor whose parameters match the arguments used in the function call.)

The statement :


	CAdd()
	{
		cout << "A default constructor is called " << endl;
	}

declares a default constructor. If the statement CAdd myobj2; is called the default constructor is called (note: no number between the parentheses. (Remember, the compiler will call the constructor whose parameters match the arguments used in the function call.)

The statement :


	~CAdd()
	{
		cout << "Destructing " << one << endl;
	}

declares a destructor to deallocate the objects. Note the tilde (~).

At the end of the program objects are deallocated in the reverse order in which the constructors are called.

Note:Constructors cannot be called explicitly as if they were regular member functions. They are only executed when a new object of that class is created. Destructors are automatically called when an object is destroyed. For example when an object is dynamically assigned and it is released using the delete operator. (Destructors are really handy when you use dynamic memory).

Pointers to classes

Pointer can also be used with classes. (A class becomes a valid type once declared).

Take a look at the example:


	CAdd * ptr_add;

Now ptr_add is a pointer to an object of class CAdd. As we did with structures we can use the arrow operator (->) of indirection to refer to a member of an object pointed by a pointer.

Take a look at an example:


	#include<iostream>
	using namespace std;

	class CAdd
	{
		private:
			int x, y;
		public:
			void add(int,int);
			int ret() { return x+y; }
	};

	void CAdd::add(int a, int b)
	{
		x = a;
		y = b;
	}

	int main()
	{
		CAdd my_object, *ptr_add;
		ptr_add= new CAdd;

		my_object.add(4,4);
		ptr_add->add(2,2);

		cout << my_object.ret() << endl;
		cout << ptr_add->ret() << endl;

		return 0;
	}

In the table below you can read some pointer and class operators:

Expression Explanation
*a pointed by
a
&a address of
a
a.b member b of object
a
a->b member b of object
pointed by a
(*a).b member b of object
pointed by a (same as the previous one)
a[0] first object pointed
by a
a[1] second object pointed
by a
a[n] (n+1)th object pointed
by a

Be sure that you understand the logic of all of these expressions before proceeding with the next tutorial.

That is all for this tutorial.

This entry was posted in C++ Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site. Tweet This! Tweet This! or use to share this post with others.

There are currently 8 responses to “C++ Classes – Constructors and destructors”

Why not let us know what you think by adding your own comment!

  1. Rugnar on March 6th, 2010:

    Please, give example for usage of destructor.

  2. admin on March 6th, 2010:

    @Rugnar, below you will find an example as requested:

    #include <iostream>
    using namespace std;

    // A class CRectArea with a constructor and descructor
    // to determine the area of a rectangle.
    class CRectArea {
    int *width, *height;
    public:
    CRectArea (int,int);
    ~CRectArea ();
    int areaofrect () {
    return (*width * *height);
    }
    };

    // Constructor
    CRectArea::CRectArea (int x, int y) {

    //Dynamically allocate some memory
    width = new int;
    height = new int;

    *width = x;
    *height = y;
    }

    // Destructor
    CRectArea::~CRectArea () {
    //Delete the allocate memory
    delete width;
    delete height;
    }

    int main () {
    CRectArea myrectangle (2,2);
    cout << “The area of the rectangle is: ” << myrectangle.areaofrect() << endl;
    return 0;
    }

    In this example we want to determine the area of a rectangle. We use a constructor, where we dynamically allocate some memory for the width and height. In the destructor we delete the memory, we dynamically allocated in the constructor. Now, every time an instance of a class is created the constructor method is called (in this case: CRectArea myrectangle (2,2); The destructor is called near the end of the program.

    Where are destructors commonly used for? They are usually used to “clean up” when an object is no longer necessary, to “clean up” the mess you have create during a program.
    Hope this helps, good luck!

  3. Crazy on August 13th, 2010:

    Hi,
    Can you please explain copy constructor and its usage
    Thanks in advance

  4. admin on August 14th, 2010:

    @Crazy – We working on a tutorial to explain copy constructor and assignment operators. Give us a couple of days to come-up with some examples.

  5. mebrahten on December 6th, 2011:

    it is nice note

  6. ajay kumar on June 19th, 2012:

    Hey, Hi Admin..! I am Student of BCA and till date i was not able to understand this C or C++ but i just saw your website and the contents and honestly speaking man..! Hats off 2 u..! Coz T’day i got to know bout so many things which were der in my syllbus but aah nevaa uncdersttod coz of stupid faculties in mah colg….!

    Thankzz Man..!

    Dam Awesome Site..!
    ***** Complete deserving 5x* Site..!

  7. admin on June 27th, 2012:

    hi.. i m student.. what is the reason of pointer concept used in c .and c++ does not use?? and y in c++ used in constructing/destructing?

  8. ehtesham on January 30th, 2014:

    where the default constructor called from where it is located?

Leave a Reply: