Coupon Accepted Successfully!


Anonymous Objects

Objects are created with names. It is possible to declare objects without name. Such objects are known as anonymous objects. We learnt how to invoke constructors and destructors. When constructors and destructors are invoked, the data members of the class are initialized and destroyed, respectively. Thus, without object we can initialize and destroy the contents of the class. All these operations are carried out without object or we can also assume that the operations are carried out using an anonymous object, which exists but is hidden. The second thought is correct because if we apply pointer this (explained in Chapter 13 “Pointers and arrays”), we get the address of the object. It is not possible to invoke member function without using object but we can invoke the special member functions constructors and destructors which compulsorily exist in every class. Thus, without the use of constructor and destructor, the theory of anonymous object cannot be implemented in practice. Consider the following example:

9.19 Write a program to create an anonymous object. Initialize and display the contents of member variables.

Explanation: In the above program, class noname is declared with one integer data member. The class also has constructor, destructor, and member function. The member function show() is used to display the contents on the screen.

In function main(), no object is created. The constructor is called directly. Calling constructor directly implies creating anonymous objects. In the first call of the constructor, the member variable is initialized with 15. The constructor invokes the member function show() that displays the value of x on the screen.

It is not possible to create more than one anonymous object at a time. When constructor execution work is over destructor destroys the object. Again, the constructor with one argument is called and integer is passed to it. The member variable is initialized with 12 and it is displayed by show() function. Finally, the destructor is executed that marks the end of program.

Tip: Calling constructor directly means creating anonymous objects.

Test Your Skills Now!
Take a Quiz now
Reviewer Name