Passing arguments to a superclass constructor

2020-04-17 05:52发布

I'm just getting into derived classes, and I'm working on the famous Shape class. Shape is the base class, then I have three derived classes: Circle, Rectangle, and Square. Square is a derived class of Rectangle. I think I need to pass arguments from the derived class constructors to the base class constructor, but I'm not sure exactly how to do this. I want to set the dimensions for the shapes as I create them. Here is what I have for the base class and one derived class:

Shape(double w = 0, double h = 0, double r = 0)
{
     width = w;
     height = h;
     radius = r;
}


class Rectangle : public Shape
{
     public:
     Rectangle(double w, double h) : Shape(double w, double h)
     {
         width = w;
         height = h;
     }              
     double area();
     void display();      
};

Am I on the right track here? I'm getting the following compiler error: expected primary expression before "double", in each of the derived constructors.

2条回答
仙女界的扛把子
2楼-- · 2020-04-17 06:32

You have to change Shape(double w, double h) to Shape(w, h). You are actually calling the base constructor here.

In addition, You don't have to set width and height in the constructor body of the derived class:

  Rectangle(double w, double h) : Shape(w, h)
  {}

is enough. This is because in your initializer list Shape(w, h) will call the constructor of the base class (shape), which will set these values for you.

When a derived object is created, the following will be executed:

  1. Memory for Shape is set aside
  2. The appropriate Base constructor is called
  3. The initialization list initializes variables
  4. The body of the constructor executes
  5. Control is returned to the caller

In your example, the Shape subobject is initialized by Shape(double w = 0, double h = 0, double r = 0). In this process, all the members of the base part (width, height, radius) are initialized by the base constructor. After that, the body of the derived constructor is executed, but you don't have to change anything here since all of them are taken care of by the base constructor.

查看更多
贪生不怕死
3楼-- · 2020-04-17 06:38

Almost. Instead of redeclaring the parameters here:

Rectangle(double w, double h) : Shape(double w, double h)

You should simply "pass them through" (to give an inexact phrasing):

Rectangle(double w, double h) : Shape(w, h)
{ }
查看更多
登录 后发表回答