16.2 “const” WITH CLASS OBJECTS

In previous example, we saw the use of “const” with pointers. It is also possible to use it with class objects and class members.

16.2.1 “const” Class object

It is possible to declare an object as constant. Assume we have class Point suitably defined. Now we are allowed to declare

const Point pt1;

It declares a constant object named pt1 of type Point. You will ask me what the use of this declaration is. Well, now compiler will not allow us to modify this object. It means you cannot modify even its public data members! Well we may say that we have achieved “read only” objects.

16.2.2 “const” With data members

C++ allows us to make a data member constant. The constants are normally initialized at the declaration. ...

Get Object Oriented Programming with C++, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.