What do you mean by Virtual Function in C++:
Virtual functions are very important because they support polymorphism at run time. It is a member function that is declared within the base class but redefined inside there 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 example illustrates the use of a virtual function:
Implementation of above program:
#include<iostream>
using namespace std;
// Base class
class A
{
public:
int i;
A(int x) // Base class constructor
{
i=x;
}
virtual void func() // virtual function in base class
{
cout<<"Using A's function";
cout<<i<<endl;
}
};
// derived class B of base class A
class B : public A
{
public:
B(int x): A(x) // derived class B's constructor
{
}
void func() // virtual function which is redefined in derived class B
{
cout<<"Using B's function";
cout<<i*i<<endl;
}
};
// derived class C of base class A
class C : public A // derived class C's constructor
{
public:
C(int x): A(x)
{
}
void func() // virtual function which is redefined in derived class B
{
cout<<" Using C's function";
cout<<i+i<<endl;
}
};
// declaration of main function with different function call
int main()
{
A *p;
A a_obj(10);
B b_obj(10);
C c_obj(10);
p = &a_obj;
p->func();
p = &b_obj;
p->func();
p = &c_obj;
p->func();
return 0;
}
The program output is tested on www.jdoodle.com
Output:
Using A's function : 10
Using B's function : 100
Using C's function : 20
Thanks
Mukesh Rajput
Post A Comment:
0 comments: