I was wondering to know about virtual function, its uses and how to create a pure virtual function in c and c++ programming language. Being programmer I am looking to collect more and more c programming questions and answers to enhance my skills in C language. Can anyone answers my query.
Looking forward for positive replies.
If there are member functions with same name in base class and derived class, virtual functions gives programmer capability to call member function of different class by a same function call depending upon different context. This feature in C++ programming is known as polymorphism which is one of the important feature of OOP.If a base class and derived class has same function and if you write code to access that function using pointer of base class then, the function in the base class is executed even if, the object of derived class is referenced with that pointer variable.
If you want to execute the member function of derived class then, you can declare it in the base class which makes that function existing in appearance only but, you can’t call that function. In order to make a function virtual, you have to add keyword virtual in front of a function.Let’s understand this with an exapmle.
#include <iostream>
using namespace std;
class B
{
public:
virtual void display() /* Virtual function */
{ cout<<"Content of base class.\n"; }
};
class D1 : public B
{
public:
void display()
{ cout<<"Content of first derived class.\n"; }
};
class D2 : public B
{
public:
void display()
{ cout<<"Content of second derived class.\n"; }
};
int main()
{
B *b;
D1 d1;
D2 d2;
/* b->display(); // You cannot use this code here because the function of base class is virtual. */
b = &d1;
b->display(); /* calls display() of class derived D1 */
b = &d2;
b->display(); /* calls display() of class derived D2 */
return 0;
}
OUTPUT
Content of first derived class.
Content of second derived class.
After the function of base class is made virtual, code b->display( ) will call the display( ) of the derived class depending upon the content of pointer.
In this program, display( ) function of two different classes are called with same code which is one of the example of polymorphism in C++ programming using virtual functions.
I hope this helps.
Thanks Shubham for help me for this issues.