The const Objects
In the previous chapter, we have studied the constant functions. The const declared functions do not allow the operations that alter the values. In the same fashion, we can also make the object constant by the keyword const. Only constructor can initialize data member variables of constant object. The data member of constant objects can be read-only and any effort to alter values of variables will generate an error. The data members of constant object are also called read-only data members. The constant object can access only constant functions. If constant object tries to invoke a non-member function, an error message will be displayed.
9.12 Write a program to declare constant object. Also, declare constant member function and display the contents of member variables.
Explanation: In the above program, class ABC is declared with one member variable and one constant member function show(). The constructor ABC is defined to initialize the member variable. The show() function is used to display the contents of member variable. In main(), the object x is declared as constant with one integer value. When object is created, the constructor is executed and value is assigned to data member. The object x invokes the member function show().