Virtual Functions
Virtual Functions
Polymorphism
Kashiram Pokharel
• In C++ the meaning of polymorphism is the ability to access different
implementations of a program element (eg function, operator )using
the same name
• Polymorphism means state of having many form
“the same thing but in different forms”
• Early binding or static binding or static linking. Also known as compile time
polymorphism, simply means that an object is bound to its function call at
compile time
• Static binding is achieved using function overloading and operator
overloading
• Even though there are two or more functions with same name, compiler
uniquely identifies each function depending on the parameters passed to
those functions.
• The overloaded member functions are selected for invoking by matching
arguments, both type and number. This information is known to the compiler
at the compile time, therefore, compiler can select appropriate function
• The example of compile time polymorphism are
• Function overloading
• Operator overloading
Compile time polymorphism
• selection of the function for the virtual function takes place at run time. If a member function
is selected while program is running then this is called run time polymorphism.
• the function link with a class after compilation, therefore, this is called late binding or dynamic
binding. This is called dynamic binding because function is selected dynamically at runtime.
• For example
a) virtual function
• A virtual function is a member function that you expect to be redefined in derived classes.
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 means existing in effect but not in reality or Virtual means existing in appearance but
not in reality.
• When virtual functions are used, a program that appears to be calling a function of one
class may in reality be calling a function of a different class.
• A function is declared virtual by writing keyword ‘virtual’ in front of function header. A virtual
function uses a single pointer to base class pointer to refer to all the derived objects.
Need of virtual function:
• Virtual functions are useful when we have number of objects of different classes but
want to put them all on a single list and perform operation on them using same
function call.
• if a function present in Base class is overridden in derived class then Inheritance has
ambiguity .So virtual keyword is used to overcome this and at run time which
function to call can be decided by using Base class pointer to point to either Base
class object or Derived class object
• Virtual functions allow us to create a list of base class pointers and call methods of any
of the derived classes without even knowing kind of derived class object.
• only functionality can be redefined in derived class, not the interface of the function.
A Base class pointer can be used to point to Base Class Object as well as Derived Class
Object.
Note:
• When we use the same function name in both the base and derived classes, the
function in base class declared as virtual function. The virtual function is invoked at run
time based on the type of pointer.
Example:
#include <iostream.h>
class B
{
public : Int main( )
virtual void show( ) {
{ B *P ;
cout<< “This is in class B”<<endl ; D1 obj1 ;
}} ; // end of class B D2 obj2 ;
class D1 : public B B objbase ;
{ p=&objbase ;
public : p-> show( ) ; //base class function
void show( ) p=&obj1 ;
{ p ->show( ) ; //derived class function
cout<< “This is in class D1”<<endl ; p=&obj2 ;
} p-> show( ) ;
}; // end of class D1 }
class D2 : public B Output:
{ This is in class B
public: This is in class D1
void show( ) This is in class D2
{
cout<< “This is in class D2”<<endl ;
}} ; //end of class D2
Example 2:
#include <iostream.h>
class polygon class triangle: public polygon
{ {
protected :
int width, height ; public:
public : int area( )
void setdata(int a, int b) {
{ return (width*height / 2) ;
width=a; }
height=b; }; //end of class triangle
} void main( )
virtual int area( ) {
{ rectangle r ;
return 0 ; triangle t ;
} polygon p ;
}; //end of class polygon polygon *p1=&r ;
class rectangle: public polygon polygon *p2=&t ;
{ polygon *p3=&p ; Output:
public: p1-> setdata(4,5) ;
int area( ) p2 ->setdata(4,5) ; 20
{ p3 ->setdata(4,5) ;
return (width*height) ; cout<<p1-> area( )<<endl ; 10
} cout<<p2 ->area( )<<endl ;
cout<<p3 ->area( )<<endl ; 0
}; //end of class rectangle }
Pure Virtual function:
• Virtual inside the base class and redefine it in the derived class. But
the function defined inside the base class B is seldom (rarely) used for
performing any task. These functions only serve as placeholder. Such
functions are called do-nothing function or pure virtual function.
• In above example, ‘=’ sign has nothing to do with assignment
operation and value 0 is not assigned anything. This simply informs
the compiler that function will be pure i.e. it will have no definition
relative to base class.
• It should be noted that class containing pure virtual function cannot
be used to create objects of its own. Such classes are known as
Abstract classes.
pure virtual function
#include <iostream.h> int main( )
#include <conio.h> {
class B //Base class Dd;
{
public: B *P ;
virtual void show( )=0 ; // pure virtual P=&d ;
function
}; P-> show( ) ;
class D : public B //derived class return 0 ;
{
public: getch( ) ;
void show( ) }
{
cout<< “Inside derived class”; Output:
} Inside derived class
};
Rules for Virtual Functions:
• If a function is made virtual function, following things should be considered:
• A virtual function must be a member of certain class.
• Such function cannot be a static member. But it can be a friend of another class.
• A virtual function is accessed by using object pointer.
• A virtual function must be defined, even though it may not be used.
• The prototypes of the virtual in the base class and the corresponding member function in the
derived class must be same. If not same, then C++ treats them as overloaded functions
having same name, different arguments) thereby the virtual function mechanism is ignored.
• The base pointer can point to any type of the derived object, but vice-versa is not true i.e.
the pointer to derived class object cannot be used to point the base class object.
• Incrementing or decrementing the base class pointer (pointing derived object) will
• not make it point to the next object of derived class object.
• If a virtual function is defined in the base class, it is not compulsory to redefine it in the
derived class. In such case, the calls will invoke base class function.
• There cannot be virtual constructors in a class but there can be virtual destructors
Early & Late Binding:
Early Binding Late Binding
1. It is also known as compile time polymorphism. It is 1. It is also known as run time polymorphism. It is
called so because compiler selects the appropriate called so because the appropriate member functions
member function for particular function call at the are selected while the program is executing or running.
compile time.
2. The information regarding which function to invoke 2. The compiler doesn’t know which function to bind
that matches a particular call is known in advance with particular function call until program is executed
during compilation. Thatis why it is also called as early i.e. the function is linked with particular class much
binding later after compilation.
3. The function call is linked with particular function at 3. The selection of appropriate function is done
compiler time statically. So, it is also called static dynamically at run time, so it is also called dynamic
binding binding..
This type of binding can be achieved using function 4. This type of binding is achieved using virtual function
overloading and operator overloading. and base class pointer.
Abstract class:
• By definition, an abstract class in C++ is a class that has at least one pure
virtual function (i.e., a function that has no definition).
• The classes inheriting the abstract class must provide a definition for the
pure virtual function; otherwise, the subclass would become an abstract
class itself.
• An abstract class is a class that is designed to be specifically used as a
base class. An abstract class contains at least one pure virtual function.
You declare a pure virtual function by using a pure specifier (= 0) in the
declaration of a virtual member function in the class declaration
• Example:
class AB {
public: virtual void f() = 0;
};
Function overriding:
• achieved at run time
• It is the redefinition of base class function in its derived class with same
signature i.e return type and parameters.
• It can only be done in derived class.
• When a member function of a base class is redefined in its derived class
with the same parameters and return type, it is called function overriding
in C++.
• If we use an object of the derived class to call this function, the function
defined in the derived class is invoked. The base class function is said to
be overridden.
class BaseClass int main()
{ {
public:
virtual void Display() DerivedClass dr;
{
cout << "\nThis is Display() method of BaseClass"; BaseClass &bs = dr;
} bs.Display();
void Show()
{ dr.Show();
cout << "\nThis is Show() method of BaseClass"; }
}
}; Output:
class DerivedClass : public BaseClass This is Display() method of DerivedClass
{ This is Show() method of BaseClass
public:
// Overriding method - new working of
// base class's display method
void Display()
{
cout << "\nThis is Display() method of DerivedClass";
}
};
Basis Function Overloading Function Overriding