0
0
C++programming~7 mins

Virtual functions in C++

Choose your learning style9 modes available
Introduction

Virtual functions let a program choose the right function to run when using a base class pointer or reference. This helps when you want different behaviors for different types of objects.

When you have a base class pointer pointing to different derived class objects and want to call the correct function for each.
When you want to write flexible code that can work with many types of objects sharing a common base.
When you want to change or extend behavior in derived classes without changing the base class code.
Syntax
C++
class Base {
public:
    virtual void functionName();
};

The keyword virtual before a function means it can be overridden in derived classes.

Virtual functions must be members of a class.

Examples
This base class has a virtual function sound that can be changed in derived classes.
C++
class Animal {
public:
    virtual void sound() {
        std::cout << "Some sound" << std::endl;
    }
};
The derived class Dog overrides the virtual function to provide its own behavior.
C++
class Dog : public Animal {
public:
    void sound() override {
        std::cout << "Bark" << std::endl;
    }
};
Using a base class pointer to a derived object calls the Dog version of sound because it is virtual.
C++
#include <iostream>

int main() {
    Animal* a = new Dog();
    a->sound();
    delete a;
    return 0;
}
Sample Program

This program shows how virtual functions let the program call the right sound function depending on the actual object type, even when using base class pointers.

C++
#include <iostream>

class Animal {
public:
    virtual void sound() {
        std::cout << "Some sound" << std::endl;
    }
    virtual ~Animal() = default;
};

class Dog : public Animal {
public:
    void sound() override {
        std::cout << "Bark" << std::endl;
    }
};

class Cat : public Animal {
public:
    void sound() override {
        std::cout << "Meow" << std::endl;
    }
};

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

    animal1->sound();  // Calls Dog's sound
    animal2->sound();  // Calls Cat's sound

    delete animal1;
    delete animal2;
    return 0;
}
OutputSuccess
Important Notes

If a function is not virtual, the base class version is called even if the pointer points to a derived object.

Use override keyword in derived classes to help catch mistakes.

Remember to make destructors virtual if you use virtual functions to avoid memory leaks.

Summary

Virtual functions allow dynamic choice of function at runtime based on object type.

They enable polymorphism, making code flexible and reusable.

Always use virtual in base class and override in derived classes for clarity.