Chapter 26. Making Constructive Arguments

In This Chapter

  • Creating and invoking a constructor with arguments

  • Overloading the constructor

  • Constructing data members with arguments

  • Looking forward to a new format of constructor in the 2009 standard

The Student class in Chapter 25 was extremely simple — almost unreasonably so. After all, a student has a name and a student ID as well as a grade point average and other miscellaneous data. I chose GPA as the data to model in Chapter 25 because I knew how to initialize it without someone telling me — I could just zero out this field. But I can't just zero out the name and ID fields; a no-named student with a null ID probably does not represent a valid student. Somehow I need to pass arguments to the constructor to tell it how to initialize fields that start out with a value that's not otherwise predictable.

Constructors with Arguments

C++ allows the program to define a constructor with arguments as shown here:

class Student
     Student(const char* pszNewName, int nNewID)
         int nLength = strlen(pszNewName) + 1;
         pszName = new char[nLength];
         strcpy(pszName, pszNewName);
         nID = nNewID;
         delete[] pszName;
         pszName = 0;

     char* pszName;
     int    nID;

Here the arguments to the constructor are a pointer to an ASCIIZ string that contains the name of the new student and the student's ID. The constructor first allocates space for the student's name. It then copies the new name into the pszName data member. Finally, it copies over ...

Get Beginning Programming with C++ For Dummies® now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.