Defined Virtual Function

In object-oriented programming, polymorphism is a key principle that allows objects of different classes to be treated as objects of a common base class. This allows you to write code that can work with different types of objects in a uniform manner, providing flexibility and reusability in your code.

One of the mechanisms to achieve polymorphism in many programming languages is through the use of virtual functions (also known as virtual methods or dynamic binding). A virtual function is a member function in a base class that is declared with the “virtual” keyword. Subclasses that inherit from the base class can override the virtual function to provide their own implementation.

Key points to understand the virtual function in C++

  1. Virtual Function Declaration: To declare a function as virtual, you use the virtual keyword in the function declaration in the base class. For example:
class Base {
public:
    virtual void virtualFunction() {
        // Base class implementation
    }
};

2. Function Overriding: When a virtual function is redefined in a derived class with the same signature (name and parameters), it is said to be overridden. The derived class provides its own implementation for the function.

3. Late Binding (Dynamic Binding): When you call a virtual function through a base class pointer or reference, the function to be executed is determined at runtime based on the actual type of the object being pointed to or referenced. This process is called late binding or dynamic binding.

Example of Virtual Function

#include <iostream>

class Animal {
public:
    virtual void makeSound() {
        std::cout << "Animal makes a sound\n";
    }
};

class Dog : public Animal {
public:
    void makeSound() override {
        std::cout << "Dog barks\n";
    }
};

class Cat : public Animal {
public:
    void makeSound() override {
        std::cout << "Cat meows\n";
    }
};

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

    animal1->makeSound(); // Output: Dog barks
    animal2->makeSound(); // Output: Cat meows

    delete animal1;
    delete animal2;

    return 0;
}

In this example, we have a base class Animal with a virtual function makeSound(). The subclasses Dog and Cat both inherit from Animal and override the makeSound() function with their own implementations.

When we create objects of Dog and Cat and store them in pointers of type Animal*, we can call the makeSound() method on these pointers. Since makeSound() is declared as virtual in the base class, the appropriate version of the function is called based on the actual type of the object (whether it’s a Dog or a Cat). This is known as dynamic dispatch or runtime polymorphism.

Without the virtual keyword, the function would be statically bound (resolved at compile-time) based on the pointer type and would always call the Animal version of makeSound() even if the object being pointed to is a Dog or a Cat. Virtual functions ensure that the correct function is called at runtime, allowing for polymorphic behavior.

Advantages of Virtual Functions

Virtual functions offer several advantages in C++ development:

  • Polymorphism: Virtual functions enable polymorphic behavior, allowing flexible and extensible code.
  • Abstraction: By using abstract classes and pure virtual functions, C++ promotes abstraction, focusing on what an object does rather than how it does it.
  • Code Organization: Virtual functions help organize code into meaningful and maintainable classes, improving code readability and maintainability.

Guidelines for Using Virtual Functions

While virtual functions are powerful, they should be used judiciously. Here are some guidelines to follow:

  • Don’t Overuse: Avoid using virtual functions for small, fixed-size classes or ones that won’t be extended.
  • Use Abstract Classes: When creating a base class with virtual functions, consider making it an abstract class to prevent direct instantiation.
  • Avoid Multiple Inheritance: Be cautious when using multiple inheritance with virtual functions, as it can lead to ambiguity and design complexities.

FAQs

Q1. What are virtual functions in C++?

A: Virtual functions in C++ are functions that enable runtime polymorphism, allowing the appropriate function to be called based on the actual object’s type.

Q2. Can a regular function be made virtual in C++?

A: No, regular functions are resolved at compile-time, and they cannot be made virtual.

Q3. What is an abstract class in C++?

A: An abstract class is a class that contains at least one pure virtual function and cannot be instantiated. It serves as a base class for other classes.

Q4. What is the advantage of using virtual functions?

A: Virtual functions provide polymorphism and abstraction, promoting flexibility and maintainability in C++ code.


more related content on Object Oriented Programming

JOIN OUR NEWSLETTER
And get notified everytime we publish a new blog post.