A virtual function is a member function of class that
is declared within a base class and again redefined (overridden) in derived class.
Functions are declared with a virtual keyword
in base class.
They are mainly used
to achieve runtime polymorphism.
Virtual
functions should be accessed using pointer or reference of base class type to
achieve run time polymorphism
Use:
When you want to use same function name in both the base and derived
class, then the function in base class is declared as virtual by using
the virtual keyword and again re-defined this
function in derived class without using virtual keyword.
Syntax:
virtual return_type function_name()
{
//statements
}
Example 1: Without Using virtual keyword
#include
<iostream.h>
#include <conio.h>
class A
{
public:
void display()
{
cout<<"base class
function"<<endl;
}
};
class B : public A
{
public:
void display()
{
cout<<" derive class
function";
}
};
void main()
{
clrscr();
A *ptr1;
B obj2;
ptr1=&obj2;
ptr1->display();
getch();
}
Output :
base class function
Note:
When we use Base class's pointer to hold Derived class's object, base
class pointer or reference will always call the base class function
Example
2:Using virtual keyword
#include
<iostream.h>
#include<conio.h>
class A
{
public:
virtual void display()
{
cout<<"base class
function"<<endl;
}
};
class B : public A
{
public:
void display()
{
cout<<" derive class
function";
}
};
void main()
{
clrscr();
A obj1;
B obj2;
A *ptr1;
ptr1=&obj1;
ptr1->display(); // call base class function
ptr1=&obj2;
ptr1->display(); // call derive class function
getch();
}
Output:
base class function
derive class
function
Python is an open-source, high level, interpreted programming language which offers great opportunities for object-oriented programming. Choosing a python training program from Red Prism Group, which is best training institute for python in noida.
ReplyDelete