CONST OBJECTS

The Volume() function that you defined for the CBox class does not alter the object for which it is called; neither does a function such as getHeight() that returns the value of the m_Height member. Likewise, the Compare() function in the previous example didn’t change the class objects at all. This may seem at first sight to be a mildly interesting but largely irrelevant observation, but it isn’t — it’s quite important. Let’s think about it.

You will undoubtedly want to create class objects that are fixed from time to time, just like values such as pi or inchesPerFoot that you might declare as type const double. Suppose you wanted to define a CBox object as const — because it was a very important standard-sized box, for instance. You might define it with the following statement:

const CBox standard(3.0, 5.0, 8.0);

Now that you have defined your standard box having dimensions 3 × 5 × 8, you don’t want it messed about with. In particular, you don’t want to allow the values stored in its data members to be altered. How can you be sure they won’t be?

Well, you already are. If you declare an object of a class as const, the compiler will not allow any member function to be called for it that might alter it. You can demonstrate this quite easily by modifying the declaration for the object, cigar, in the previous example to:

const CBox cigar(8.0, 5.0, 1.0);            // Declare cigar box

If you try recompiling the program with this change, it won’t compile. You will see the error ...

Get Ivor Horton's Beginning Visual C++ 2012 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.