Virtual Function in C++

Virtual functions gives programmers 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. For this purpose we make a class LEP_A and then 2 classes further drived from here and virtual function of A class override in both classes.

Source Code

#include <iostream>
using namespace std;
class LEP_A
{
 public:
 virtual void show()      /* Virtual function */
{
 cout<<"Virtual Function on A class.\n";
}
};
class LEP_B : public LEP_A
{
public:
void show()
{
cout<<"B Drived Class Function .\n";
}};
class LEP_B2 : public LEP_A
{
public:
void show()
        {
cout<<" B2 Drived Class Function .\n";
}
};
int main()
{
cout<<"\n\n\t ************** VIRTUAL FUNCTION ************* \n\n ";
LEP_A *a;
LEP_B B;
LEP_B2 B2;
a = &B;
a->show();
a = &B2;          
a->show();
return 0;
}

Output of the Program

Virtual Function in C++

Share on Google Plus

About Asad

Asad Niazi is Software Engineer , Programmer, Web Developer and a young mentor of BloggersTown and PProgramming. Asad Love to writes about Technology, Programming, Blogging and make money online.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment