Search code examples
c++inheritanceaccess-modifiersclass-visibility

Can a sub-class affect visibility of virtual methods?


Let's say I have a fist class

class Walker {
public:
   Walker();
   virtual ~Walker();
   virtual void Step();
};

Then a second one, deriving from the former

class Mecha : public Walker {
public:
   Mecha();
   virtual ~Mecha();
private:
   virtual void Step();
};

Is that private modifier on Step() any useful? Mecha::Step() can still be called as Walker::Step(), isn't it? Shouldn't there be a warning as I'm trying to change the nature of the super-class through the definition of its sub-class?


Solution

  • Can a sub-class affect visibility of virtual methods?

    Yes, they can change the visibility of the methods.

    Is that private modifier on Step() useful?

    Depends. It primarily affects the client of the code.

    Increasing the visibility (e.g. going from protected to public) may be useful, but comes with a warning on it's use - the implementer of the base class interface desired that method to be internal to the hierarchy, making it external could break things... (possible implementations of the template method pattern come to mind).

    Principally, changing the visibility doesn't affect the polymorphic nature of the virtual method - it still is overridden in the derived class. It does however affect the caller. Changing the method to private limits client code to calling the method from a pointer or reference to the base class and not the derived.

    Mecha m;
    //m.Step(); // fails to compile
    Walker& w = m;
    w.Step(); // still calls Mecha::Step()
    

    Further, changing the method to protected would allow further sub-classes to call it.