ricefieldboy
ricefieldboy

Reputation: 377

Default constructor in derived classes

i am going over my old exams to study for finals and have noticed some stuff I still do not understand.

class Shape
{
  private:
  int center_x, int center_y;
  public:
  Shape (int x, int y) : center_x(x), center_y(y); {} //constructor initializer
}
class Rectangle : public Shape
{
  private:
  int length, width;
  public:
  Rectangle(): //this is where i have trouble, I am supposed to fill in missing code here
  //but shape does not have a default constructor, what am i supposed to fill in here?
  Rectangle (int x, int y, int l, int w) : Shape(x,y);{length = l; width = w;}
}

Thanks

Upvotes: 2

Views: 1152

Answers (3)

user1084944
user1084944

Reputation:

You're asking the wrong question. You should be asking

What should a default constructed Rectangle be?

Once you answer this question, one of the following will happen:

  • It will become clear how to initialize the Shape base
  • You will realize that Rectangle should not have a default constructor
  • You will realize that something needs to be redesigned

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

There are two approaches. Either you call the base class construcor in the mem-initializer list of the default constructor with some default values as for example (I use zeroes as the default values):

Rectangle() : Shape( 0, 0 ), length( 0 ), width( 0 ) {}

Or you can delegate all the work from the default constructor to the constructor with parameters.

For example

Rectangle() : Rectangle( 0, 0, 0, 0 ) {}

Take into account that class definitions shall be ended with semicolon.:)

Upvotes: 5

Christophe
Christophe

Reputation: 73376

You can assume that no coordinates are defined for your default rectangle. So it would be:

Rectangle(): Shape(x,y) , length(0), width(0) { }

Upvotes: 0

Related Questions