What do you mean by Virtual Function in Object Oriented programming?
Virtual functions are important because they support polymorphism at run time. A virtual function is a member function that is declared within the base class but redefined inside the derived class. To create a virtual function we precede the function declaration with the keyword virtual. Thus we can assume the model of “one interface multiple method”. The virtual function within the base class defines the form of interface to that function. It happens when a virtual function is called through a pointer.
The following is an example that illustrates the use of a virtual function:
Program Code:
#include<iostream>
using namespace std;
class A
{
public:
int i;
A(int x)
{
i=x;
}
// declaration of virtual function with definition in base class A
virtual void func()
{
cout<<"Using A version of function : ";
cout<<i<<endl;
}
};
// derived class B of base class A
class B : public A
{
public:
B(int x):A(x){}
// redeclaration of virtual function with definition in derived class B of base class A
void func()
{
cout<<"Using B version of function : ";
cout<<i*i<<endl;
}
};
// derived class C of base class A
class C : public A
{
public:
C(int x): A(x){}
// redeclaration of virtual function with definition in derived class C of base class A
void func()
{
cout<<"Using C version of function : ";
cout<<i+i<<endl;
}
};
// definition of main() function with different member function call of class A, B and C
int main()
{
A *p; // object pointer of base class A
A obj(100); // object of class A
B obj1(60); // object of class B
C obj2(70); // object of class C
p=&obj; // passing address of object of class A to pointer
p->func();
p=&obj1;// passing address of object of class B to pointer
p->func();
p=&obj2;// passing address of object of class C to pointer
p->func();
return 0;
}
The program output is tested on www.jdoodle.com
Output:
Using A version of function : 100
Using B version of function : 3600
Using C version of function : 140
Thanks
Mukesh Rajput
Post A Comment:
0 comments: