CLASS CONSTRUCTORS

In the previous program example, you declared the CBox objects, box1 and box2, and then laboriously worked through each of the data members for each object in order to assign an initial value to it. This is unsatisfactory from several points of view. First of all, it would be easy to overlook initializing a data member, particularly with a class that had many more data members than our CBox class. Initializing the data members of several objects of a complex class could involve pages of assignment statements. The final constraint on this approach arises when you get to defining data members of a class that don’t have the attribute public — you won’t be able to access them from outside the class at all. There has to be a better way and, of course, there is — it’s known as the class constructor.

What Is a Constructor?

A class constructor is a special function in a class that is responsible for creating new objects. A constructor, therefore, provides the opportunity to initialize objects as they are created and to ensure that data members only contain valid values. A class may have several constructors, enabling you to create objects in various ways.

You have no leeway in naming the constructors in a class — they all have the same name as the class in which they are defined. The CBox() function, for example, is a constructor for our CBox class. A constructor has no return type. It’s wrong to specify a return type for a constructor; you must not even write it as ...

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.