When you declare a virtual function that you really tell the compiler, this is what you want the function to behave polymorphically. That is, from your example, if we have the following:
A* foo = new B(); foo->f();
it will call function B "f", not function "f". To take it further, if we have C that inherits from B, as you said:
class C : public B{} B* foo = new C(); foo->f():
it calls B "f". If you defined it in C, it would call method C.
To explain the different behavior of virtual and non-virtual, take this example:
struct Foo{ virtual void f(); void g(); }; struct Bar{ virtual void f(); void g(); }; Foo* var = new Bar(); var->f();
has the meaning?
source share