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.

228Part III: Introduction to ClassesAvoiding the “object declaration trap”Look again at the way the Student objectswere declared in the ConstructorWDefaultsexample:Student noName;Student freshMan(“Smell E. Fish”);Student xfer(“Upp R. Classman”, 80, 2.5);All Student objects except noName aredeclared with parentheses surrounding thearguments to the constructor. Why is noNamedeclared without parentheses?To be neat and consistent, you may think youcould have declared noName as follows:Student noName();Unfortunately, C++ allows a declaration withonly an open and close parentheses. However,it doesn’t mean what you think it does at all.Instead of declaring an object noName of classStudent to be constructed with the defaultconstructor, it declares a function that returnsan object of class Student by value. Surprise!The following two declarations demonstratehow similar the new C++ format for declaring anobject is to that of declaring a function. (I thinkthis was a mistake, but what do I know?) Theonly difference is that the function declarationcontains types in the parentheses, whereas theobject declaration contains objects:Student thisIsAFunc(int);Student thisIsAnObject(10);If the parentheses are empty, nothing can differentiatebetween an object and a function. Toretain compatibility with C, C++ chose to make adeclaration with empty parentheses a function.(A safer alternative would have been to forcethe keyword void in the function case, but thatwould not have been compatible with existingC programs.)Constructing Class MembersIn the preceding examples, all data members are of simple types, such as intand float. With simple types, it’s sufficient to assign a value to the variablewithin the constructor. Problems arise when initializing certain types of datamembers, however.Constructing a complex data memberMembers of a class have the same problems as any other variable. It makesno sense for a Student object to have some default ID of zero. This is trueeven if the object is a member of a class. Consider the following example://// ConstructingMembers - a class may pass along arguments// to the members’ constructors//#include #include

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

Saved successfully!

Ooh no, something went wrong!