Chapter 25. Getting Objects Off to a Good Start

In This Chapter

  • Creating a constructor

  • Examining limitations on how constructors are invoked

  • Reviewing an example constructor

  • Constructing data members

  • Introducing the "not constructor" — the destructor

Normally an object is initialized when it is created as in the following:

double PI = 3.14159;

This is true of class objects as well:

class Student
{
   public:
     int nHours;
     double dGrade;
};

Student s = {0, 0.0};

However, this is no longer possible when the data elements are declared protected if the function that's creating the objects is not a friend or member of the class (which, in most cases it would not be).

Some other mechanism is required to initialize objects when they are created, and that's where the constructor comes in.

The Constructor

One approach to initializing objects with protected members would be to create an init() member function that the application could call when the object is created. This init() function would initialize the object to some legal starting point. In fact, that's exactly what I do in Chapter 24.

This approach would work, but it doesn't exactly fit the "microwave oven" rules of object-oriented programming because it's akin to building a microwave oven that requires you to hit the Reset button before you could do anything with it. It's as if the manufacturer put some big disclaimer in the manual: "DO NOT start any sequence of commands without FIRST depressing the RESET button. Failure to do so may cause the oven ...

Get Beginning Programming with C++ For Dummies® 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.