C++ Programming & Tutorials for Beginners

Virtual Functions

Home  »  C++ Programming  »  Virtual Functions


     Virtual functions play an important role in object oriented programming. Ordinary functions use the concept of early binding. However virtual functions help in late binding. A virtual function in one that does not really exist but it appears real in some parts of a program. The concept of pointers paly a vital role in virtual functions. To make a member function virtual, the keyboard virtual is used before the function declaration.

The general syntax of the virtual function declaration is given below :
class user_defince_name
{
  private:
    ____________________
    ____________________
  public:
    virtual data_type function1 ( arguments );
    virtual data_type function1 ( arguments );
    virtual data_type function1 ( arguments );
    ____________________
    ____________________
};

In the above given syntax, function1,function2 and function3 are virtual functions. The compiler differentiate the ordinary and virtual functions by the keyword virtual which is written before the virtual functions.

for example:
class demo
{
  private:
  int a,b;
  public:
    virtual void input();
    virtual void sum();
    virtual void output();
};

The concept of virtual functions is related to late binding. In other words, the virtual functions employ late binding by allocating memory space during execution time and not during compilation time. In case of virtual functions, when a pointer of base class is defined in the main() function and derived class object's address is passed onto the base class pointer, then calling the overridden function will invoke the derived class member function and not the base class member fucntion. The virtual fucntions are the base of late binding and are closely related to the concept of polymorphism. The simple example of virtual fucntion is given below :





Output




Previous
Next Post »