Tuesday, November 12, 2013

Virtual Functions in C++

A virtual function is a member function that is declared within a base class and redefined by a derived class. To create a virtual function, precede the function's declaration in the base class with the keyword virtual. When a class containing a virtual function is inherited, the derived class redefines the virtual function to fit its own needs.

When accessed "normally," virtual functions behave just like any other type of class member function. However, what makes virtual functions important and capable of supporting run-time polymorphism is how they behave when accessed via a pointer. When a base pointer points to a derived object that

contains a virtual function, C++ determines which version of that function to call based upon the type of object pointed to by the pointer. And this determination is made at run time. Thus, when different objects are pointed to, different versions of the virtual function are executed. The same effect applies to base-class references.

To begin, examine this short example:

#include <iostream>
using namespace std;
class base {
public:
virtual void vfunc() {
cout << "This is base's vfunc().\n";
}
};

class derived1 : public base {
public:
void vfunc() {
cout << "This is derived1's vfunc().\n";
};

class derived2 : public base {
public:
void vfunc() {
cout << "This is derived2's vfunc().\n";
}
};

int main()
{
base *p, b;
derived1 d1;
derived2 d2;
p = &b;
p->vfunc();
p = &d1;
p->vfunc();
p = &d2;
p->vfunc();
return 0;
}

No comments:

Post a Comment