Chapter 25

Getting Objects Off to a Good Start

In This Chapter

arrow Creating a constructor

arrow Examining limitations on how constructors are invoked

arrow Reviewing an example constructor

arrow Constructing data members

arrow 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 — see Chapter 24 for more about these relationships).

Some other mechanism is required to initialize objects when they’re 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 ...

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