0

I would like to better understand how the virtual qualifier is propagated in a class family. Consider the following code:

struct Parent {
  void func() { cout << "Parent!" << endl; }
};

struct Child : Parent {
  void func() { cout << "Child!" << endl; }
};

int main() {  
  Parent* pc = new Child;
  pc->func(); // prints "Parent!"
}    

The Child override of func() is not called because the Parent function is not virtual. Simple enough.

In the following example, I added an interface to Parent and I don't understand why adding it bound the call from Parent::func() to Child:func() since this last one is called from a Parent pointer.

struct Interface {
  virtual void func() = 0;
};

struct Parent : Interface {
  void func() { cout << "Parent!" << endl; }
};

struct Child : Parent {
  void func() { cout << "Child!" << endl; }
};

int main() {  
  Parent* pc = new Child;
  pc->func(); // prints "Child!"
}

I was thinking that the construction of new Child would go in the following order :

  1. Interface in constructed, declaring a pure virtual func()
  2. Parent is constructed, overriding func() (I thought that at this point, the abstract construction would be "satisfied" and "done")
  3. Child is constructed, declaring it's own func()implementation
VincentDM
  • 469
  • 6
  • 17
  • 5
    the method is virtual in `Child` also, methods do not need the `virtual` keyword to be virtual, but only the base has to declare it as virtual. ...trying to find the duplicate – 463035818_is_not_an_ai Apr 29 '19 at 12:54
  • related: https://stackoverflow.com/questions/13972462/why-is-the-virtuality-of-methods-implicitly-propagated-in-c?rq=1 – 463035818_is_not_an_ai Apr 29 '19 at 12:55
  • this is what I was looking for, unfortunately not really a good duplicate, but maybe good enough: https://stackoverflow.com/questions/4895294/c-virtual-keyword-for-functions-in-derived-classes-is-it-necessary – 463035818_is_not_an_ai Apr 29 '19 at 12:55
  • 2
    Use [`override`](https://en.cppreference.com/w/cpp/language/override) when you mean to override a `virtual` function. If it compiles then you actually did override. Otherwise the compiler will complain that you used `override` without overriding anything. It makes this type of code more readable, especially when you have `-Werror=suggest-override` to enforce that style. – nwp Apr 29 '19 at 12:58

0 Answers0