Bar and Box are derived classes of Foo and Foo has a virtual function F() and Bar and Box both have function F(). From what I understand, polymorphism correctly allows Bar.F() instead of Box.F() or Box.F() instead of Bar.F() to override Foo.F() using some runtime routine without knowing whether your object is a Bar or a Box. It’s something like this:
Foo * boxxy = new Box;
boxxy->F();
The last line will call the right F() (in this case, Box.F()) independent of whether boxxy is a Box or a Bar or a Foo (in which case the implementation of the virtual Foo.F() is called).
Do I understand this right? And what changes if boxxy is a Box pointer? And what happens if the derived class doesn’t have an override for F()? Lastly, to avoid implementing a function for a base class but still allow polymorphism, do you just write an empty function body and declare it virtual? Thanks.
Nearly right – consider this inheritance tree:
If you now make a pointer like this:
You’ll get a nice compiler error, since a
Boxcan’t be converted to aBar. 🙂So it’s only
Foo<->BarandFoo<->Box, neverBar<->Box.Next, when
boxxyis aBoxpointer, it will only ever call theBox::Ffunction, if it is provided.And last, to force subclasses to implement a certain function, you declare it
pure virtual, like this:Now subclasses (in this case
BarandBox), must implementFunc, else they will fail to compile.