Chapter 16. Making Constructive Arguments

In This Chapter

  • Making argumentative constructors

  • Overloading the constructor

  • Creating objects by using constructors

  • Invoking member constructors

  • Constructing the order of construction and destruction

Aclass represents a type of object in the real world. For example, in earlier chapters, I use the class Student to represent the properties of a student. Just like students, classes are autonomous. Unlike a student, a class is responsible for its own care and feeding — a class must keep itself in a valid state at all times.

The default constructor presented in Chapter 15 isn't always enough. For example, a default constructor can initialize the student ID to 0 so that it doesn't contain a random value; however, a Student ID of 0 is probably not valid.

C++ programmers require a constructor that accepts some type of argument to initialize an object to other than its default value. This chapter examines constructors with arguments.

Outfitting Constructors with Arguments

C++ enables programmers to define a constructor with arguments, as shown here:

class Student
{
  public:
    Student(const char *pName);

    // ...class continues...
};

Using a constructor

Conceptually, the idea of adding an argument is simple. A constructor is a member function, and member functions can have arguments. Therefore, constructors can have arguments.

Remember, though, that you don't call the constructor like a normal function. Therefore, the only time to pass arguments to the constructor ...

Get C++ For Dummies®, 6th Edition now with O’Reilly online learning.

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