You are on page 1of 2

Object Oriented Programming Lab Week 13 CUSIT

Object Oriented Programming


Virtual Functions
A virtual function is a member function which is declared in base class and overridden in derived
class. A virtual function is declared using the keyword virtual.

When you refer to a derived class object using a pointer of base class, you can call a virtual function
for that object and execute the derive class version for it.

Virtual function ensures the correct version of function is called for an object, regardless the type of
pointer used for function call. The resolving of function is done at Run time so that is why it is called
Run time Polymorphism.

Example

1|Page Furqan Nasir


Object Oriented Programming Lab Week 13 CUSIT

Program explained in video lecture

Defining in a base class a virtual function, with another version in a derived class, signals to the
compiler that we don't want static linkage for this function.

What we do want is the selection of the function to be called at any given point in the program to be
based on the kind of object for which it is called. This sort of operation is referred to as dynamic
linkage, or late binding.

Abstract Class/ Pure Virtual Function


Sometimes implementation of all functions cannot be provided in base class. E.g Area of different
shapes. Such class is called Abstract class.

A pure virtual function (sometimes called abstract function) is a virtual function which don’t have
any implementation. It is only declared in base class. A pure virtual function is declared by assigning
0 in declaration.

Example

Only change in above program is declaration of virtual function in base class.

Some points to remember


 Virtual function is a type of function overriding so for function overriding, virtual function is
not must, function overriding can be fulfilled without using virtual function.
 A class is abstract if it has at least one pure virtual function.
 We can have pointers of abstract class data type.
 Abstract classes cannot be instantiated (cannot make objects).
 If we don’t override the pure virtual function in derive class, it also becomes abstract class.

2|Page Furqan Nasir

You might also like