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.

266Part IV: InheritanceBefore control passes beyond the open brace of the constructor forGraduateStudent, control passes to the proper constructor of Student. IfStudent were based on another class, such as Person, the constructor forthat class would be invoked before the Student constructor got control. Likea skyscraper, the object is constructed starting at the “base”-ment class andworking its way up the class structure one story at a time.Just as with member objects, you often need to be able to pass arguments tothe base class constructor. The example program declares the subclass constructoras follows:GraduateStudent(char *pName, Advisor& adv, float qG = 0.0): Student(pName), advisor(adv), qualifierGrade(qG){// whatever construction code goes here}Here the constructor for GraduateStudent invokes the Student constructor,passing it the argument pName. C++ then initializes the members advisorand qualifierGrade before executing the statements within the constructor’sopen and close braces.The default constructor for the base class is executed if the subclass makesno explicit reference to a different constructor. Thus, in the following codesnippet the Pig base class is constructed before any members of LittlePig,even though LittlePig makes no explicit reference to that constructor:class Pig{public:Pig() : pHouse(null){}protected:House* pHouse;};class LittlePig : public Pig{public:LittlePig(float volStraw, int numSticks, int numBricks): straw(volStraw), sticks(numSticks), bricks(numBricks){ }protected:float straw;int sticks;int bricks;};Similarly, the copy constructor for a base class is invoked automatically.

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

Saved successfully!

Ooh no, something went wrong!