Passing arguments to a superclass constructor

前端 未结 2 617
一整个雨季
一整个雨季 2021-01-22 02:04

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

相关标签:
2条回答
  • 2021-01-22 02:38

    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.

    0 讨论(0)
  • 2021-01-22 02:41

    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)
    { }
    
    0 讨论(0)
提交回复
热议问题