11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 17: Making Constructive Arguments 225protected:char name[40];int semesterHours;float gpa;};int main(int argcs, char* pArgs[]){// the following invokes three different constructorsStudent 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 resultssystem(“PAUSE”);return 0;Because the object noName appears with no arguments, it’s constructed usingthe constructor Student::Student(). This constructor is called the default,or void, constructor. (I prefer the latter name, but the former is the morecommon one, so I use it in this book — I’m a slave to fashion.) The freshManis constructed using the constructor that has only a char* argument, and thexferStudent uses the constructor with three arguments.Notice how similar all three constructors are. The number of semester hoursand the GPA default to zero if only the name is provided. Otherwise, there isno difference between the two constructors. You wouldn’t need both constructorsif 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 declarationto be used in the event that the argument is not present. By addingdefaults to the last constructor, all three constructors can be combined intoone. For example, the following class combines all three constructors into asingle, clever constructor://// ConstructorWDefaults - multiple constructors can often// be combined with the definition// of default arguments//#include #include #include #include using namespace std;

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

Saved successfully!

Ooh no, something went wrong!