Course Content
C++ Introduction
0/1
C++ Variables & Constants
0/1
C++Scope of Variable
0/1
C++ Keywords & Identifiers
0/1
C++ Data Types
0/1
C++ Basic I/O
0/1
C++ Type Conversion
0/1
C++ Operators
0/1
C++ Comments
0/1
C++ If-else
0/1
C++ Ternary Operator
0/1
C++ for Loop
0/1
C++ Ranged for Loop
0/1
C++ while/do-while Loop
0/1
C++ break Statement
0/1
C++ Continue Statement
0/1
C++ switch Statement
0/1
C++ goto Statement
0/1
C++ Functions
0/1
C++ User-defined Functions
0/1
C++ Default Arguments
0/1
C++ Storage Class
0/1
C++ Recursion
0/1
C++ Return by Reference
0/1
C++ Arrays
0/1
C++ Multi-dimentional Arrays
0/1
C++ Arrays & Function
0/1
C++ String
0/1
C++ Structure
0/1
C++ Structure & Functions
0/1
C++ Pointers to Structure
0/1
C++ Pointers
0/1
C++ Void Pointers
0/1
C++ Pointers & Arrays
0/1
C++ Pointers & Functions
0/1
C++ Dynamic Memory Allocation
0/1
C++ OOPs Concepts
0/1
C++ Objects and Class
0/1
C++ Constructors
0/1
C++ Destructors
0/1
C++ Constructor Overloading
0/1
C++ Objects & Function
0/1
C++ Enumeration
0/1
C++ Inheritance
0/1
C++ Inheritance Access Control
0/1
C++ Inheritance Types
0/1
C++ Polymorphism
0/1
C++ Function Overloading
0/1
C++ Function Overriding
0/1
C++ Operator Overloading
0/1
C++ Friend Function
0/1
C++ Virtual Function
0/1
C++ Abstract Class & Pure Virtual Function
0/1
C++ Encapsulation
0/1
C++ Abstraction
0/1
C++ Templates
0/1
C++ Exception Handling
0/1
C++ Multithreading
0/1
C++ Standard Library
0/1
C++ Programming Tutorials
About Lesson

C++ Virtual Function

In this tutorial, we will learn about C++ virtual function and its use with the help of examples.

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. This especially applies to cases where a pointer of base class points to an object of a derived class. you can call a virtual function for that object and execute the derived class’s version of the function.

For example, consider the code below:

class Base {
public:
void display() {
// Some code
}
};

class Derived : public Base {
public:
void display() {
// Some code
}
};

Later, if we create a pointer of Base type to point to an object of Derived class and call the display() function, it calls the display() function of the Base class.

In other words, the member function of Base is not overridden.

int main() {
Derived d1;
Base* b1 = &d1;

// calls function of Base class
b1->display();

return 0;
}

In order to avoid this, we declare the display() function of the Base class as virtual by using the virtual keyword.

class Base {
public:
virtual void display() {
// Some code
}
};

Virtual functions are an integral part of polymorphism in C++. To learn more, check our tutorial on C++ Polymorphism.


Late Binding in C++

In Late Binding function call is resolved at runtime. Hence, now compiler determines the type of object at runtime, and then binds the function call. Late Binding is also called Dynamic Binding or Runtime Binding.


Features of Virtual Functions

  • 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 Run-time.

Example 1: C++ program to demonstrate the working of virtual Function

#include <iostream>
using namespace std;

class Base {
   public:
    virtual void display() {
        cout << "Base Function" << endl;
    }
};

class Derived : public Base {
   public:
    void display() {
        cout << "Derived Function" << endl;
    }
};

int main() {
    Derived d1;

    // pointer of Base type that points to derived1
    Base* b1 = &d1;

    // calls member function of Derived class
    b1->display();

    return 0;
}

Output

Derived Function

Here, we have declared the display() function of Base as virtual.

So, this function is overridden even when we use a pointer of Base type that points to the Derived object d1.

display() of Derived class is called because display() of Base class is virtual.


C++ override Identifier

C++ 11 has given us a new identifier override that is very useful to avoid bugs while using virtual functions.

This identifier specifies the member functions of the derived classes that override the member function of the base class.

For example,

class Base {
   public:
    virtual void display() {
        // Some code
    }
};

class Derived : public Base {
   public:
    void display() override {
        // Some code
    }
};

If we use a function prototype in Derived class and define that function outside of the class, then we use the following code:

class Derived : public Base {
   public:
    // function prototype
    void display() override;
};

// function definition
void Derived::display() {
        // Some code
    }

Use of override in C++

When using virtual functions. it is possible to make mistakes while declaring the member functions of the derived classes.

Using the override identifier prompts the compiler to display error messages when these mistakes are made.

Otherwise, the program will simply compile but the virtual function will not be overridden.


Some of these possible mistakes are:

  • Functions with incorrect names: For example, if the virtual function in the base class is named display(), but we accidentally name the overriding function in the derived class as diplay().
  • Functions with different return types: If the virtual function is, say, of void type but the function in the derived class is of int type.
  • Functions with different parameters: If the parameters of the virtual function and the functions in the derived classes don’t match.
  • No virtual function is declared in the base class.

Use of C++ Virtual Functions

Suppose we have a base class Animal and derived classes Dog and Cat.

Suppose each class has a data member named type. Suppose these variables are initialized through their respective constructors.

class Animal {
   private:
    string type;
    ... .. ...
    public:
      Animal(): type("Animal") {}
    ... .. ...
};

class Dog : public Animal {
   private:
    string type;
    ... .. ...
    public:
      Animal(): type("Dog") {}
    ... .. ...
};

class Cat : public Animal {
   private:
    string type;
      ... .. ...
    public:
      Animal(): type("Cat") {}
    ... .. ...
};

Now, let us suppose that our program requires us to create two public functions for each class:

  1. getType() to return the value of type
  2. display() to display the value of type

We could create both these functions in each class separately and override them, which will be long and tedious.

Or we could make getType() virtual in the Animal class, then create a single, separate display() function that accepts a pointer of Animal type as its argument. We can then use this single function to override the virtual function.

class Animal {
    ... .. ...
   public:
    ... .. ...
    virtual string getType {...}
};

... .. ...
... .. ...

void display(Animal* ani) {
    cout << "Animal: " << ani->getType() << endl;
}

This will make the code shortercleaner, and less repetitive.


Example 2: C++ program to Demonstrate virtual Function

#include <iostream>
#include <string>
using namespace std;

class Animal {
   private:
    string type;

   public:
    // constructor to initialize type
    Animal() : type("Animal") {}

    // declare virtual function
    virtual string getType() {
        return type;
    }
};

class Dog : public Animal {
   private:
    string type;

   public:
    // constructor to initialize type
    Dog() : type("Dog") {}

    string getType() override {
        return type;
    }
};

class Cat : public Animal {
   private:
    string type;

   public:
    // constructor to initialize type
    Cat() : type("Cat") {}

    string getType() override {
        return type;
    }
};

void display(Animal* ani) {
    cout << "Animal: " << ani->getType() << endl;
}

int main() {
    Animal* animal1 = new Animal();
    Animal* dog1 = new Dog();
    Animal* cat1 = new Cat();

    display(animal1);
    display(dog1);
    display(cat1);

    return 0;
}

Output

Animal: Animal
Animal: Dog
Animal: Cat

Here, we have used the virtual function getType() and an Animal pointer ani in order to avoid repeating the display() function in every class.

void display(Animal* ani) {
    cout << "Animal: " << ani->getType() << endl;
}

In main(), we have created 3 Animal pointers to dynamically create objects of AnimalDog and Cat classes.

// dynamically create objects using Animal pointers
Animal* animal1 = new Animal();
Animal* dog1 = new Dog();
Animal* cat1 = new Cat();

We then call the display() function using these pointers:

  1. When display(animal1) is called, the pointer points to an Animal object. So, the virtual function in Animal class is executed inside of display().
  2. When display(dog1) is called, the pointer points to a Dog object. So, the virtual function is overridden and the function of Dog is executed inside of display().
  3. When display(cat1) is called, the pointer points to a Cat object. So, the virtual function is overridden and the function of Cat is executed inside of display().

Rules for Virtual Functions

  1. Virtual functions cannot be static and also cannot be a friend function of another class.
  2. Virtual functions should be accessed using pointer or reference of base class type to achieve run time polymorphism.
  3. The prototype of virtual functions should be same in base as well as derived class.
  4. They are always defined in base class and overridden in derived class. It is not mandatory for derived class to override (or re-define the virtual function), in that case base class version of function is used.
  5. A class may have virtual destructor but it cannot have a virtual constructor.
Exercise Files
No Attachment Found
No Attachment Found
error: Content is protected !!