简体   繁体   中英

C++ Inheritence: Avoid calling default constructor of base class

In the following code I am calculating the area of triangle. Once I declare the object tri1 the width and height are initialized twice.

First: The default constructor of the base class is called and values width = 10.9 ; height = 8.0 ; are automatically assigned to the triangle.

Then: In triangle construct width = a; and height = b; happens.

But, my question is: Is there any way not to call any constructor from a base class?

class polygon {
protected:
    float width, height;
public:
    polygon () {width = 10.9; height = 8.0;}
    void set_val (float a, float b) {width = a; height = b;}
    polygon (float a, float b) : width(a), height(b) {cout<<"I am the polygon"<<endl;}
};

class triangle: public polygon {
public:
    triangle (float a, float b) {cout<<"passed to polygon"<<endl; width = a; height = b;} 
    float area () {return width*height/2;}
};

int main () {
    triangle tri1 {10, 5};
    cout<<tri1.area()<<endl;
}

You're not doing anything in the derived constructor. A derived class calls the default constructor of the base class implicitly and there's no way to avoid it. Instead, you should delegate the derived constructor's parameters to the base one.

First, a small problem. Your code initialises the variables inside the constructor, in C++ we use initialisation lists like so:

class polygon {
protected:
    float width, height;
public:
    polygon(): width(10.9), height(8.0) {}
    void set_val (float a, float b) {width = a; height = b;}
    polygon (float a, float b) : width(a), height(b) {cout<<"I am the polygon"<<endl;}
};

On to the real problem; To fix your issue, make the derived class call the base constructor explicitly:

class triangle: public polygon {
public:
    triangle(float a, float b): polygon(a, b) {cout<<"passed to polygon"<<endl;}
    float area () {return width*height/2;}
};

After that, it should work properly.

No, you can't avoid calling a base class constructor. You can specify which base class constructor to call in derived class though by specifying the base class constructor in the initializer list of the derived class constructor and passing arguments to the constructor which match a base class constructor prototype. From those arguments the base class constructor is deduced.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM