Anonymous Object in C++

Anonymous Object is a Object without any name.

In a C++ programming an object are created with names but It is still possible to create object without name such object are known as anonymous object.

When constructor and destructor are called, the data members are initialize and destroyed respectively.

Without object we can initialize and destroy the content of the class.

All these operations are carried out without object or we can also assume that operations are carried out using an anonymous object.

Example: Create a Simple C++ class and call it without reference variable.

  1. Create a simple class.
  2. Call a constructor from main()

Output

Note: In the above program, we have created class “A” which contains constructor and destructor.

In the main() function, no object is created.

The constructor are called directly.

Calling constructor directly means creating object but not accessing with any name. It is not possible to create more than one anonymous object at a time.                              

When constructor execution ends , destructor is executed to destroy the object.

Example: Showing student details Using Ananonyous object in C++

Steps for developing program

  1. Create a class name Student
  2. Declare private members of class
  3. Declare constructor to take arguments
  4. Assign local variable to Object variable
  5. Show student data in show()
  6. Define Destructor
  7. Call Constructor( without creating object) from main method.

Result:

Read More

  1. C++ program for student details
  2. Lowercase character to uppercase character
  3. Command Line Argument
  4. Local vs Global Object in C++
  5. Local and Nested Classes in C++
  6. Arithmetic operations using switch case
  7. Switch Case in C Programming
  8. Constructor in C++
  9. Know more about C++

Reference

C++ classes