Virtual
Virtual
Aim:
Description:
Virtual function:
A virtual function is a member function which is declared within a base class and is re-
defined (overridden) by a derived class. When you refer to a derived class object using a
pointer or a reference to the base class, you can call a virtual function for that object and
execute the derived class’s version of the function.
Virtual functions ensure that the correct function is called for an object, regardless of the
type of reference (or pointer) used for function call.
They are mainly used to achieve runtime polymorphism.
Functions are declared with a virtual keyword in base class.
The resolving of function call is done at runtime.
Syntax:
Code:
#include<iostream>
using namespace std;
class A
{
int x=5;
public:
void display( )
{
cout<<"The value of x is: "<<x<<endl;
}
};
class B:public A
{
int y=10;
public:
void display( )
{
cout<<"The value of y is: "<<y<<endl;
}
};
DepartmentofCSE Page1
int main( )
{
A *a;
B b;
a=&b;
a->display();
return 0;
}
Output:
DepartmentofCSE Page2
Pure virtual function:
Description:
Syntax:
Code:
#include <iostream>
class Base
public:
};
public:
void show()
std::cout << "Derived class is derived from the base class." << std::endl;
DepartmentofCSE Page3
};
int main()
Base *bptr;
Derived d;
bptr=&d;
bptr->show();
return 0;
Output:
DepartmentofCSE Page4