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

Chapter 17: Making Constructive Arguments 227

Defaulting Default Constructors

As far as C++ is concerned, every class must have a constructor; otherwise, you can’t create objects of that class. If you don’t provide a constructor for your class, C++ should probably just generate an error, but it doesn’t. To pro­ vide compatibility with existing C code, which knows nothing about con­ structors, C++ automatically provides a default constructor (sort of a default default constructor) that sets all the data members of the object to binary zero. Sometimes I call this a Miranda constructor — you know, “if you cannot afford a constructor, a constructor will be provided for you.”

If you define a constructor for your class, any constructor, C++ doesn’t pro­ vide the automatic default constructor. (Having tipped your hand that this isn’t a C program, C++ doesn’t feel obliged to do any extra work to ensure compatibility.)

The result is that if you define a constructor for your class but you also want a default constructor, you must define it yourself. Some code snippets help demonstrate this point. The following is legal:

class Student

{

// ...all the same stuff as before but no constructors

};

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

{

Student noName; return 0;

}

The following code snippet does not compile properly:

class Student

{

public:

Student(char *pName);

};

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

{

Student noName; return 0;

}

The seemingly innocuous addition of the Student(char*) constructor pre­ cludes C++ from automatically providing a Student() constructor with which to build object noName.