3

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?

Niall
  • 30,036
  • 10
  • 99
  • 142
PypeBros
  • 2,607
  • 24
  • 37
  • 2
    On a tangent : it's probably a good time to hear about the [`override`](http://en.cppreference.com/w/cpp/language/override) and [`final`](http://en.cppreference.com/w/cpp/language/final) specifiers :) – Quentin Aug 12 '16 at 11:31

2 Answers2

4

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.

Niall
  • 30,036
  • 10
  • 99
  • 142
  • Making Step() on Mecha private enforces the interface to be used. This can be useful to ensure more generic code being written if one would have access to both Mecha and Walker, while the Mecha class should become an implementation detail on the long term. – JVApen Aug 12 '16 at 11:42
3

No, making Step() private does not change the polymorphic behaviour. There's no warning since the language explicitly allows this. (But note that Java doesn't).

But it does prevent your being able to write Mecha::Step() explicitly unless you code that in a member function of Mecha.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483