Virtual Function
Virtual Function
Unit 3
Virtual Function
• Value of x is : 5
• In the above example, *a is the base class pointer. The
pointer can only access the base class members but not
the members of the derived class.
• Although C++ permits the base pointer to point to any
object derived from the base class, it cannot directly
access the members of the derived class.
• Therefore, there is a need for virtual function which
allows the base pointer to access the members of the
derived class.
virtual function Example
#include <iostream>
{
public:
virtual void display()
{
cout << "Base class is invoked"<<endl;
}
};
class B:public A
{
public:
void display()
{
cout << "Derived Class is invoked"<<endl;
}
};
int main()
{
A *a; //pointer of base class
B b; //object of derived class
a = &b;
a->display(); //Late Binding occurs
}
Output
• Derived Class is invoked
Pure Virtual Function
• A virtual function is not used for performing any task. It only
serves as a placeholder.
• When the function has no definition, such function is known as
"do-nothing" function.
• The "do-nothing" function is known as a pure virtual
function.
• A pure virtual function is a function declared in the base class
that has no definition relative to the base class.
• A class containing the pure virtual function cannot be used to
declare the objects of its own, such classes are known as abstract
base classes.
• The main objective of the base class is to provide the heirarchy
to the derived classes and to create the base pointer used for
achieving the runtime polymorphism.
• Pure virtual function can be defined as:
virtual void display() = 0;
Example
#include <iostream>
using namespace std;
class Base
{
public:
virtual void show() = 0;
};
class Derived : public Base
{
public:
void show()
{
cout << "Derived class is derived from the base class." << endl;
}
};
int main()
{
Base *bptr;
Derived d;
bptr = &d;
bptr->show();
return 0;
}
Output