PypeBros PypeBros - 1 year ago 74
C++ Question

Can a sub-class affect visibility of virtual methods?

Let's say I have a fist class

class Walker {
virtual ~Walker();
virtual void Step();

Then a second one, deriving from the former

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

Is that
modifier on
any useful?
can still be called as
, 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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download