Search code examples
c++inheritanceconstructorinitializationprotected

Impossible to access protected function in the initialization of the derived class's constructor


I'm trying to implement a class Union which inherits directly from the class Shape (Union is a shape composed of multiple shapes).

The (protected) constructor of Shape takes a Point as input (representing the center of the shape). To construct a Union object, the only input is a list of shapes (const vector<const Shape>). To implement the constructor of Union, I wanted to use an initialization list, as detailed herebelow

class Union : Shape
{
public:
     Union(const std::vector<const Shape> shapes): 
     Shape(shapes[0].get_center()), shapes(shapes) {};
     ...
private:
     const std::vector<const Shape> shapes;

}

with get_center() a protected virtual function of class Shape.

class Shape
{
protected:
     Shape (const Point& center) : center(center) {};
     virtual const Point& get_center() const =0;
     ...
private:
     const Point center;
}

However, when I call get_center() in the initialization list of Union constructor, there is an error saying that "get_center() is a protected member of Shape".

Can someone explain me why I cannot call get_center() from the subclass Union (which should have inherited the function) ?

Thank you!

P.S.: If I set the function get_center() to public, there is no error anymore.


Solution

  • Issue can be reduced to that

    struct Base
    {
    protected:
        int i = 0;
    };
    
    struct Derived : Base
    {
        static void foo(Base& b)
        {
            b.i = 42; // Error
        }
    
        static void bar(Derived& d)
        {
            d.i = 42; // Ok
        }
    };
    

    Demo

    You can only access protected members through the derived class.