Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C++ For Dummies (2004) [eng].pdf
Скачиваний:
84
Добавлен:
16.08.2013
Размер:
8.09 Mб
Скачать

Chapter 17

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 ear­ lier 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 16 isn’t always enough. For example, a default constructor can initialize the student ID to zero so that it doesn’t contain a random value; however, a Student ID of 0 is probably not valid. It’s up to the class to make sure that the ID is initialized to a legal value when the object is created.

C++ programmers require a constructor that accepts some type of argument in order 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(char *pName);

// ...class continues...

};

222 Part III: Introduction to Classes

Justifying constructors

Something as straightforward as adding arguments to the constructor shouldn’t require much justification, but let me take a shot at it anyway. First, allowing arguments to constructors is convenient. It’s a bit silly to make pro­ grammers construct a default object and then immediately call an initializa­ tion function to store data in it. A constructor with arguments is like one-stop shopping — sort of a full-service constructor.

Another more important reason to provide arguments to constructors is that it may not be possible to construct a reasonable default object. Remember that a constructor’s job is to construct a legal object (legal as defined by the class). If some default object is not legal, the constructor isn’t doing its job.

For example, a bank account without an account number is probably not legal. (C++ doesn’t care one way or the other, but the bank might get snippy.) You could construct a numberless BankAccount object and then require that the application use some other member function to initialize the account number before it’s used. This “create now/initialize later” approach breaks the rules, however, because it forces the class to rely on the application for initialization.

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 is when the object is created. For example, the following program creates an object s of the class Student by calling the Student(char*) constructor. The object s is destructed when the function main() returns.

//

// ConstructorWArg - provide a constructor with arguments

//

#include <cstdio> #include <cstdlib> #include <iostream> using namespace std;

const int MAXNAMESIZE = 40; class Student

{

public:

Student(char* pName)

{

strncpy(name, pName, MAXNAMESIZE); name[MAXNAMESIZE - 1] = ‘\0’;

Chapter 17: Making Constructive Arguments 223

semesterHours = 0; gpa = 0.0;

}

// ...other public members...

protected:

char name[MAXNAMESIZE]; int semesterHours; float gpa;

};

int main(int argcs, char* pArgs[])

{

Student s(“O. Danny Boy”);

Student* pS = new Student(“E. Z. Rider”);

//wait until user is ready before terminating program

//to allow the user to see the program results system(“PAUSE”);

return 0;

}

The constructor looks like the constructors shown in Chapter 16 except for the addition of the char* argument pName. The constructor initializes the data members to their empty start-up values, except for the data member name, which gets its initial value from pName.

The object s is created in main(). The argument to be passed to the con­ structor appears in the declaration of s, right next to the name of the object. Thus, the student s is given the name Danny in this declaration. The closed brace invokes the destructor on poor little Danny.

The arguments to the constructor appear next to the name of the class when the object is allocated off the heap.

Many of the constructors in this chapter violate the “functions with more than three lines shouldn’t be inlined” rule. I decided to make them inline anyway because I think they’re easier for you to read that way. Aren’t I a nice guy?

Placing Too Many Demands on the Carpenter: Overloading the Constructor

I can draw one more parallel between constructors and other, more normal member functions in this chapter: Constructors can be overloaded.

224 Part III: Introduction to Classes

Overloading a function means to define two functions with the same short name but with different types of arguments. See Chapter 6 for the latest news on function overloading.

C++ chooses the proper constructor based on the arguments in the declara­ tion of the object. For example, the class Student can have all three con­ structors shown in the following snippet at the same time:

//

//OverloadConstructor - provide the class multiple

//

ways to create objects by

//

overloading the constructor

//

 

#include <cstdio>

 

#include <cstdlib>

 

#include <iostream>

 

#include <strings.h>

 

using namespace std;

const int MAXNAMESIZE = 40; class Student

{

public:

Student()

{

cout << “constructing student no name” << endl; semesterHours = 0;

gpa = 0.0; name[0] = ‘\0’;

}

Student(char *pName)

{

cout << “constructing student “ << pName << endl; strncpy(name, pName, MAXNAMESIZE); name[MAXNAMESIZE - 1] = ‘\0’;

semesterHours = 0; gpa = 0;

}

Student(char *pName, int xfrHours, float xfrGPA)

{

cout << “constructing student “ << pName << endl; strncpy(name, pName, MAXNAMESIZE); name[MAXNAMESIZE - 1] = ‘\0’;

semesterHours = xfrHours; gpa = xfrGPA;

}

~Student()

{

cout << “destructing student” << endl;

}

Chapter 17: Making Constructive Arguments 225

protected:

char name[40];

int semesterHours; float gpa;

};

int main(int argcs, char* pArgs[])

{

//the following invokes three different constructors Student noName;

Student freshman(“Marian Haste”);

Student xferStudent(“Pikumup Andropov”, 80, 2.5);

//wait until user is ready before terminating program

//to allow the user to see the program results system(“PAUSE”);

return 0;

}

Because the object noName appears with no arguments, it’s constructed using the constructor Student::Student(). This constructor is called the default, or void, constructor. (I prefer the latter name, but the former is the more common one, so I use it in this book — I’m a slave to fashion.) The freshMan is constructed using the constructor that has only a char* argument, and the xferStudent uses the constructor with three arguments.

Notice how similar all three constructors are. The number of semester hours and the GPA default to zero if only the name is provided. Otherwise, there is no difference between the two constructors. You wouldn’t need both con­ structors if you could just specify a default value for the two arguments.

C++ enables you to specify a default value for a function argument in the dec­ laration to be used in the event that the argument is not present. By adding defaults to the last constructor, all three constructors can be combined into one. For example, the following class combines all three constructors into a single, clever constructor:

//

//ConstructorWDefaults - multiple constructors can often

//

be combined with the definition

//

of default arguments

//

 

#include <cstdio>

 

#include <cstdlib>

 

#include <iostream>

 

#include <strings.h>

 

using namespace std;

 

226 Part III: Introduction to Classes

const int MAXNAMESIZE = 40; class Student

{

public:

Student(char *pName = “no name”, int xfrHours = 0,

float xfrGPA = 0.0)

{

cout << “constructing student “ << pName << endl; strncpy(name, pName, MAXNAMESIZE); name[MAXNAMESIZE - 1] = ‘\0’;

semesterHours = xfrHours; gpa = xfrGPA;

}

~Student()

{

cout << “destructing student “ << endl;

}

// ...other public members...

protected:

char name[MAXNAMESIZE]; int semesterHours; float gpa;

};

int main(int argcs, char* pArgs[])

{

//the following invokes three different constructors Student noName;

Student freshman(“Marian Haste”);

Student xferStudent(“Pikumup Andropov”, 80, 2.5);

//wait until user is ready before terminating program

//to allow the user to see the program results system(“PAUSE”);

return 0;

}

Now all three objects are constructed using the same constructor; defaults are provided for nonexistent arguments in noName and freshMan.

In earlier versions of C++, you couldn’t create a default constructor by pro­ viding defaults for all the arguments. The default constructor had to be a separate explicit constructor. Although this restriction was lifted in the stan­ dard (it seems to have had no good basis), some older compilers may still impose it.