J247
J247

Reputation: 23

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.

Upvotes: 2

Views: 87

Answers (1)

Andrey Semashev
Andrey Semashev

Reputation: 10606

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.

Upvotes: 4

Related Questions