Q6) Write a C++ program using virtual function.
Aim:
To implement C++ program using virtual function.
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:
Virtual void function_name( )
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:
Sometimes implementation of all function cannot be provided in a base class because
we don’t know the implementation. Such a class is called abstract class.
For example, let Shape be a base class. We cannot provide implementation of function
draw() in Shape, but we know every derived class must have implementation of draw().
Similarly an Animal class doesn’t have implementation of move() (assuming that all
animals move), but all animals must know how to move. We cannot create objects of
abstract classes.
A pure virtual function (or abstract function) in C++ is a virtual function for which we
can have implementation, But we must override that function in the derived class,
otherwise the derived class will also become abstract class .
A pure virtual function is declared by assigning 0 in declaration.
Syntax:
Virtual void display( ) = 0;
Code:
#include <iostream>
using namespace std;
class Base
public:
virtual void show() = 0;
};
class Derived : public Base
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