Search code examples
c++inheritanceprotectedcomposite

Can some members of a class be accessible only by base classes?


I have a Widget class and a CompositeWidget that is derived from it. CompositeWidget adds child management behaviour. The Widget constructor takes a CompositeWidget* parameter as the widget parent. I need to use this parent pointer to access some functionality within the CompositeWidget. For example:

Widget::Widget(CompositeWidget* parent)
{
    parent_->AddChild(*this);
}

This forces me to create a public method CompositeWidget::AddChild. Is is possible to keep this interface private to the class hierarchy (a little like a reverse-protected access - limited to base classes)? Am I making a design faux pas in thinking about the problem like this?

Edit: I am trying to avoid friendship (if it's possible in this case).


Solution

  • Use the friend keyword.

    class Widget { ... };
    
    class CompositeWidget {
      friend class Widget;
    };
    

    However, you can alternatively insert the virtual method AddChild on the Widget class.