Say class B derives from class A. That both declare f(). f remains safe and secure. Hence f are only known as inside A and inside B. Does f() have to be declared virtual?

In other words: say C derives from B derives from A. B and A declare protected non-virtual f(). Will a phone call to f() in C and B resolve to B::f() as well as in A to A::f()?

For the reason that situation, must we always avoid virtual for protected people to possess static resolution? Is done instantly? Thanks!

As lengthy because the call to f() is completed in a function based on A (and never overloaded/reimplemented in B or C), the this pointer resolves to A* and for that reason A::f() is known as. So no, you'll still require a virtual function within this situation.

Proclaiming your protected method virtual is essential when you wish polymorphic behavior (a good example to this is actually the Template Method pattern), and will be prevented whenever you don't. However, within the latter situation you shouldn't shadow the function with another function getting exactly the same signature within the subclass, or else you get puzzling behavior (such as the one you describe inside your second paragraph) which reveals the chance for subtle bugs.

I'm a little rusty on my small C++ however i would state that "static resolution" would simply be guaranteed whenever you declare the technique private and therefore you'll need virtual along with protected inside your scenario...


class A {
  void f() { std::cout << "A::f\n"; }

class B : public A {
  void f() { std::cout << "B::f\n"; }

As lengthy because the compiler recognizes that an item is really a b -, it'll call f() in B. But, this isn't always the situation:

void callF(A* a)

B b;
callF(&b);  // prints A::f

If you would like functions like callF to call the right f() function, allow it to be virtual. Generally, you are making functions virtual if it seems sensible to override these questions descendant class. This really is frequently the situation for protected functions.