11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Defaulting Default ConstructorsChapter 17: Making Constructive Arguments 227As 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 foryour class, C++ should probably just generate an error, but it doesn’t. To providecompatibility with existing C code, which knows nothing about constructors,C++ automatically provides a default constructor (sort of a defaultdefault constructor) that sets all the data members of the object to binaryzero. Sometimes I call this a Miranda constructor — you know, “if you cannotafford a constructor, a constructor will be provided for you.”If you define a constructor for your class, any constructor, C++ doesn’t providethe automatic default constructor. (Having tipped your hand that thisisn’t a C program, C++ doesn’t feel obliged to do any extra work to ensurecompatibility.)The result is that if you define a constructor for your class but you also wanta default constructor, you must define it yourself. Some code snippets helpdemonstrate 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 precludesC++ from automatically providing a Student() constructor withwhich to build object noName.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!