Hi. In our series of C++ Programs for Beginners, we are posting many articles for you to Learn C++ Programming easily with strong basics. Today Another important topic on Object-Oriented Programming Language. Recently we published in an article on Constructor and Destructor in C++ with Easy Example Explanation which got a good response. So within 2 days, we are back with Constructor and Destructor Program in C++.
Some examples of the concepts of constructor and destructors:
Let us take an example program to count a total number of objects created and a total number of objects alive in the program.
First we have to understand the concept of a static variable. The static variable is not the part of the object. They are available to every object of the class (the value of the static variable is shared among the objects).
Easy Constructor and Destructor Program in C++
Now, let us see the program:
Static int count; //static variable
Explaination of C++ Constructor and Destructor Program
This program is used to count the number of objects created and object’s alive (scope is not over). We have declared count as a global variable because the count is used in every function in the class. The constructor ‘test()’ is increasing the value of count variable by one thereby showing how many objects are created and are alive. On the other hand, the destructor in the program named ’~test()’ is destroying the objects by reducing the count as the scope of the object get’s over. The ‘get_count’ returns the number of objects alive by counting them. Now you can see in the main we have declared an object ‘f4’ within the braces and the object’s scope is within the braces and it will be not be counted outside the braces. The rest of the statements will give their respective outputs.
Difference between constructor and destructor:
|Ø Constructor is used to initialize the object.||Ø Destructor is used to destroy the object that is created in memory and refers to some memory space.|
|Ø Constructors can take arguments.||Ø Destructors cannot take arguments.|
|Ø Constructor overloading is possible.||Ø Destructor overloading is not possible.|
|Ø Constructor can be of different types like default, paramaterized and copy constructor.||Ø Destructor has no types.|
|Ø Inside the constructor dynamic memory allocation can be done using ‘new’ operator.||Ø Inside destructor you can use delete operator to free the memory space i.e., dynamically created using ‘new’ operator inside the constructor.|
|Ø Constructor has the same name as that of the class name.||Ø Destructor has the same name as of class but with a tilde operator in the beginning.|
Hope you liked this article and all clear with this Constructor and Destructor Program. If you have any doubt do let us know via the comments below. Keep following our Programming tutorials Series on C++ Programs for Beginners.