简体   繁体   中英

C++ derived class unable to access protected members, unless default constructor is used

Initializing fields within constructor works:

class Shape{
protected: 
float width,height;
public:
Shape()
{
    width = 13.2;
    height = 3.2;
}
}

However when using a constructor with parameters, the code no longer compiles:

class Shape{
protected: 
float width,height;
public:
Shape(float w, float h)
{
    width = w;
    height = h;
}
}

Triangle class:

class Triangle : public Shape{
public:
float area()
{
    return (width * height / 2);
}

Here is the main function:

int main() {
Shape s = Shape();
Triangle tri;

std::cout << tri.area() << std::endl;
return 0;

This compiles and outputs result: 21.12

However when using constructor with parameters Shape s = Shape(13.2,3.2); it seems the Triangle object tri can no longer access the width and height of Shape class.

The problem is that by defining Shape 's constructor with arguments, you disable the default constructor of Shape (or more precisely, define it as deleted). And since Triangle does not define a default constructor, it also gets marked as deleted.

You need to either define the default constructor of Shape , or define a constructor of Triangle that will call the constructor of Shape with parameters w and h .

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