• Advertisement
Sign in to follow this  

c++ prob calling a base classes default constructor!

This topic is 4281 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hey everyone in my program I have two classes. One of them being class Shape, and the other being class Square which is derived from class Shape. In my class Shape i want to have a copy constructor that calls class Shape's copy constructor and sets square data. Here is my Shape.h and Square.h: Any help is appreciated :) Thanks // Shape. h #ifndef Shape_H #define Shape_H class Shape { public: Shape(); Shape(int x,int y); Shape(const Shape& tx); Shape& operator =(const Shape& tx); friend ostream& operator<< (ostream& out,const Shape& tx); protected: int XCoord; int YCoord; }; #endif // Square.h #ifndef Square_H #define Square_H #include "Shape.h" class Square : public Shape { public: Square(); Square(int x,int y,double SideOfSquare); Square(const Square& dx); Square& operator =(const Square& dx); friend ostream& operator<< (ostream& out,const Square& dx); private: double Side; }; #endif // Square_H

Share this post


Link to post
Share on other sites
Advertisement
You'll use an initialization list:

Square::Square(Square const & dx) : Shape(dx) { ... }

Share this post


Link to post
Share on other sites
ah okay i think understand, so would the following code call the base class constructor and initialize the derived class:

Square::Square(const Square& dx): Shape(dx),Side(dx.Side){}

Share this post


Link to post
Share on other sites
Yes. dx is a Square therefore dx is a Shape, so the Shape copy constructor would be called, then the derived Square class members get initialized.

Note that the order of initialization is based on the order in which the members are listed in the class definition, not in the initialization list.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement