How to create constant objects in C++ Programming Language

When there is a need to create a read-only object, the object can be declared as a constant object using the const keyword. Syntax for creating a constant object is as follows:

ClassName const object_name(params-list);

Following are the characteristics of a constant object:
  • Constant object can be initialized only through a constructor.
  • Data members of a constant object cannot be modified by any member function.
  • Constant object are read-only objects.
  • Constant objects should be accessed only through constant member functions.

Following program demonstrates a constant object:

Anonymous Objects


An object which has no name is known as an anonymous object. Syntax for creating an anonymous object is as follows:

ClassName(params-list);

An anonymous object can be created and used in any statement without using any name. It is automatically destroyed after the control moves on to the next statement. Following program demonstrates an anonymous object:

Following are the advantages of anonymous objects:
  • They result in cleaner, shorter, and efficient code.
  • There is no need to name objects which are going to be used temporarily.
  • No need to declare them.
  • Unnamed are objects are destroyed automatically after their use is over.

Take your time to comment on this article.


EmoticonEmoticon