Tuesday, May 27, 2008

What is a virtual function?

  • Virtual function is a polymorphism technique.
  • Refers to performing the same operation in a hierarchy of classes. Typically used in scenarios where the base class pointer is used to hold derived class objects and perform the same operation. Refer example below.
  • When a virtual functions is called on a base class pointer the compiler decides to defer the decision on which function to call until the program is running thereby doing late binding.
  • The actual function called at run-time depends on the contents of the pointer and not the type.
  • Internally the compiler creates a VTABLE for each which has virtual functions.
  • Addresses of virtual functions are placed in the VTABLE. If a virtual function is not redefined in the derived class, the base class function address is used in VTABLE.
  • When objects are created compiler also places a VPTR pointing to starting address of VTABLE using which the correct function is invoked.
EXAMPLE: Demonstrate the late binding using virtual functions

#include <iostream>

using namespace std;

// Base class with virtual function
class Base {
        int data1;
    public:
        Base ( int d1) { data1 = d1; }
            virtual void print() { cout << "Base" << endl; }
};

// Derived class 1
class Derived1 : public Base {
        int data2;
    public:
        Derived1(int d1, int d2) : Base (d1) { data2 = d2; }
            void print() { cout << "Derived1" << endl; }
};

// Derived class 2
class Derived2 : public Base {
    public:
        Derived2(int d1) : Base (d1) { }
            void print() { cout << "Derived2" << endl; }
};

void main()
{
    Base b(40);
    Derived1 d1(10, 20);
    Derived2 d2(30);

    Base* ptr;
    ptr=&d1;
    ptr->print();

    ptr=&d2;
    ptr->print();
}
OUTPUT:
Derived1
Derived2

2 comments :

  1. great job articulating concepts with code examples! best c++ programming refs i've seen so far. thanks!

    ReplyDelete
  2. Great Blog ! yeah it's really powerful, clean and consise !

    ReplyDelete

Contact Form

Name

Email *

Message *

Back to Top