Search code examples
c++inheritanceaccess-modifiers

Changing Function Access Mode in Derived Class


Consider the following snippet:

struct Base
{
  virtual ~Base() {}

  virtual void Foo() const = 0; // Public
};

class Child : public Base
{
  virtual void Foo() const {} // Private
};

int main()
{
  Child child;

  child.Foo(); // Won't work. Foo is private in this context.

  static_cast<Base&> (child).Foo(); // Okay. Foo is public in this context.
}

Is this legal C++? "This" being changing the virtual function's access mode in the derived class.


Solution

  • Yes, changing the access mode in derived classes is legal.

    This is similar in form but different in intent to the Non-Virtual Interface idiom. Some rationale is given here:

    The point is that virtual functions exist to allow customization; unless they also need to be invoked directly from within derived classes' code, there's no need to ever make them anything but private.

    As to why you would actually make something public in base but private in derived without private or protected inheritance is beyond me.