-1

What is the right way to do the constructors for things like this? Do I only set height and width in Rectangle?

class Rectangle {
public:
   Rectangle(int height, int width);
   int height, int width;
};

class Square : Rectangle {
   Square(int height, int width);
}
  • 1
    Take a look at http://stackoverflow.com/questions/120876/c-superclass-constructor-calling-rules. – Aiias Mar 30 '13 at 04:45

2 Answers2

1

You simply call the base class constructor at derived class's member initialization list:

class Square : Rectangle {
   Square(int height, int width): Rectangle(height, width)
   {
        //other stuff for Square
   }

}

taocp
  • 23,276
  • 10
  • 49
  • 62
0

You probably want to do it this way:

Square(int sidelength) : Rectangle(sidelength, sidelength) { }

This way you can construct Squares with a single argument and it will invoke the Rectangle constructor with that argument as width and height.

Scott Olson
  • 3,513
  • 24
  • 26