Virtual fucntion are a must to support runtime polymorphism.
class A
{
public:
virtual ~A() {}
virtual void hallo()
{ std::cout << "I'm A[" << this << "]" << std::endl; }
};
class B: public A;
{
public:
virtual void hallo()
{ std::cout << "I'm B[" << this << "]" << std::endl; }
};
int main()
{
static const size_t N = 4;
A* v[N];
for(size_t i=0; i<N; i+=2)
{
v[i] = new A;
v[i+1] = new B;
}
for(size_t i=0; i<N; ++i)
v[i]->hallo();
for(size_t i=0; i<N; ++i)
{ delete v[i]; v[i]=0; }
return 0;
}
Even if main manages just A* (and new B returns a B* that automatically convert into A* being B derived from A), making hallo and the destructor virtual makes v[i] (that is an A*) when calling hallo orwhen under delete to call the most derived method.
This is not possible without virtual functions, unless storing tales of function pointers that are noting more than the compiler generate v-tables.
The program output should be:
I'm A[0xxxxxxx]
I'm B[0yyyyyyy]
I'm A[0zzzzzzz]
I'm B[0wwwwwww]