Virtual Function

Ad

Virtual Function

Virtual Function

Virtual Function 

A virtual function is a member function which is declared in the base class using the keyword virtual and is re-defined (Overriden) by the derived class.

Note: In C++ what this means is that if we call a member function then it could cause a different function to be executed instead depending on what type of object invoked it.

Consider the following simple program as an example of runtime polymorphism. The main thing to note about the program is that the derived class’s function is called using a base class pointer.

The idea is that virtual functions are called according to the type of the object instance pointed to or referenced, not according to the type of the pointer or reference.
In other words, virtual functions are resolved late, at runtime.
Now, we’ll look at an example using both these concepts to clarify your understanding.

#include <iostream>
using namespace std;
 
// Base class
class Shape
{
public:
    Shape(int l, int w)
    {
        length = l;
        width = w;
    } // parameterized constructor
    int get_Area()
    {
        cout << "This is call to parent class area\n";
        return 1;
    }
 
protected:
    int length, width;
};
 
// Derived class
class Square : public Shape
{
public:
    Square(int l = 0, int w = 0)
        : Shape(l, w)
    {
    } // declaring and initializing derived class
      // constructor
    int get_Area()
    {
        cout << "Square area: " << length * width << '\n';
        return (length * width);
    }
};
// Derived class
class Rectangle : public Shape
{
public:
    Rectangle(int l = 0, int w = 0)
        : Shape(l, w)
    {
    } // declaring and initializing derived class
      // constructor
    int get_Area()
    {
        cout << "Rectangle area: " << length * width << '\n';
        return (length * width);
    }
};
 
int main()
{
    Shape* s;
    // Making object of child class Square
    Square sq(5, 5);
    // Making object of child class Rectangle
    Rectangle rec(4, 5);
 
    s = &sq;
    s->get_Area();
    s = &rec;
    s->get_Area();
 
    return 0;
}


A virtual function is a member function in the base class that we expect to redefine in derived classes.

Basically, a virtual function is used in the base class in order to ensure that the function is overridden. This especially applies to cases where a pointer of base class points to an object of a derived class.

For example, consider the code below:

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

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

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

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

int main() {
    Derived derived1;
    Base* base1 = &derived1;

    // calls function of Base class
    base1->print();

    return 0;
}

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

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

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

Here, we have declared the print() 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 derived1.



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. print() to print 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 print() 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 print(Animal* ani) {
    cout << "Animal: " << ani->getType() << endl;
}

This will make the code shortercleaner, and less repetitive.


Example 2: C++ virtual Function Demonstration

// C++ program to demonstrate the use of 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 print(Animal* ani) {
    cout << "Animal: " << ani->getType() << endl;
}

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

    print(animal1);
    print(dog1);
    print(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 print() function in every class.

void print(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 print() function using these pointers:

  1. When print(animal1) is called, the pointer points to an Animal object. So, the virtual function in Animal class is executed inside of print().
  2. When print(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 print().
  3. When print(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 print().

0 Response to "Virtual Function"

Post a Comment

If you have any doubts, please let me know...

Ads Atas Artikel

Ads Center 1

Ads Center 2

Ads Center 3