Virtual function:- In object oriented programming language, virtual function or method is a special type of function or method which is separately specified in inherited class. It represents inheritance concept of OOP’s. It’s main purpose is to achieve run time polymorphism by overloading a method of base class into derived class. base class object or reference can point base class object and compiler will not check overridden method. Object and method will bind at run time it is called late or dynamic binding or dynamic linking. For this purpose we will use virtual keyword before signature of method in base class.
Example:-
C++ program for virtual function.
#include<iostream.h>
#include<conio.h>
class base{
public:
void display(){
cout<<"display method of base class"<<endl;
}
virtual void show(){
cout<<"show method of base class"<<endl;
}
};
class derived:public base{
public:
//function overriding
void show(){
cout<<"show method of derived class"<<endl;
}};
void main(){
base b;
derived d;
//d.show();
clrscr();
base *ptr;
cout<<"ptr is pointing to base class"<<endl;
ptr=&b;
ptr->display();
ptr->show();
cout<<"ptr pointing to derived class"<<endl;
ptr=&d;
ptr->display();
ptr->show();
getch();
}
No comments:
Post a Comment