A virtual function is a member function of the base class and which is redefined by the derived class. When a derived class inherits the class containing the virtual function, it has ability to redefine the virtual functions. A virtual function has a different functionality in the derived class. The virtual function within the base class provides the form of the interface to the function. Virtual function implements the philosophy of one interface and multiple methods. The virtual functions are resolved at the run time. This is called dynamic binding. The functions which are not virtual are resolved at compile time which is called static binding. A virtual function is created using the keyword virtual which precedes the name of the function.
Virtual functions are accessed using a base class pointer. A pointer to the base class can be created. A base class pointer can contain the address of the derived object as the derived object contains the subset of base class object. Every derived class is also a base class. When a base class pointer contains the address of the derived class object, at runtime it is decided which version of virtual function is called depending on the type of object contained by the pointer. Here is a program which illustrates the working of virtual functions.
A Virtual function is a function whic is declared in base class using the keyword virtual. We write the body of virtual function in the derived classes. Its purpose is to tell the compiler that what function we would like to call on the basis of the object of derived class. C++ determines which function to call at run time on the type of object pointer to.
Example
class Base{
public:
virtual void fun1(void)
{
cout << "Base Class\n";
}
};
class Derived1 : public Base
{
public:
void fun1 (void)
{
cout << "Derived Class 1 \n";
}
};
class Derived2 : public Base
{
public:
void fun1 (void)
{
cout << "Derived Class 2\n";
}
};
int main(void)
{
Base b;
Base *bp;
Derived1 d1;
Derived2 d2;
bp = &b;
bp ->fun1(); //Executes the base class who function
bp = &d1;
bp ->fun1(); //Executes the Derived1 class who function
bp = &d2;
bp ->fun1(); //Executes the Derived2 class who function
}
Output
Base Class
Derived Class 1
Derived Class 2
Derived Class 1
Derived Class 2
0 comments:
Post a Comment