Sign in to follow this  
MasterDario

c++ prob calling a base classes default constructor!

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
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this