Consider the following sample code:
class Base {
public:
void f();
virtual void vf();
};
class Derived : public Base {
public:
void f();
void vf();
};
#include <iostream>
using namespace std;
void Base::f() {
cout << "Base f()" << endl;
}
void Base::vf() {
cout << "Base vf()" << endl;
}
void Derived::f() {
cout << "Derived f()" << endl;
}
void Derived::vf() {
cout << "Derived vf()" << endl;
}
int main()
{
Base b1;
Derived d1;
b1.f();
b1.vf();
d1.f();
d1.vf();
Derived d2; // Derived object
Base* bp = &d2; // Base pointer to Derived object
bp->f(); // Base f()
bp->vf(); // which vf()?
return 0;
}
The output of the run is:
Base f()
Base vf()
Derived f()
Derived vf()
Base f()
Derived vf()
Questions:
-
In the line
Base* bp = &d2, the object type is known at compile time. Then the decision of which function to use in the case ofbp->vf();can also be made at compile time right? -
Since the object type is known at compile time itself, is the power of virtual functions used in this sample program?
This program is trivial, and does indeed not demonstrate the power of virtual functions (or, more generally polymorphism) very well. Consider this change:
Here, the choice of the class depends on user-input – the compiler has no way to predict what type of object
ptrwill actually point to when the callptr->vf();is reached.