Coupon Accepted Successfully!


Private Constructors and Destructors

We learnt that when a function is declared as private, it could be invoked by the public function of the same class. So far, we declared constructors and destructors as public. The constructor and destructor can be declared as private. The constructor and destructor are automatically executed when an object is executed and when an object goes out of scope. Nevertheless, when the constructor and destructor are private, they cannot be executed implicitly, and hence, it is a must to execute them explicitly. The following program is illustrated concerning this.

9.20 Write a program to declare constructor and destructor as private and call them explicitly.

Explanation: In the above program, class A is declared. It has one data member, constructor, and destructor. The function show() is declared in public section. In function main(), a is a pointer to class A. When pointer object is created, no constructor is executed. When show() function is invoked, the constructor is invoked and its return value is assigned to pointer *this. (The pointer *this is explained in Chapter 13 “Pointers and arrays.”) Every member function holds this pointer that points to the calling object. Here, the pointer points to object a. When the pointer invokes the constructor, constructor is invoked. Consider the statement this = this->A::A(). The statement invokes the zero-argument constructors. The contents are displayed by the cout statement and again the this pointer invokes the destructor.

Test Your Skills Now!
Take a Quiz now
Reviewer Name