codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
⚡

C++ Programming

53 / 87 topics
48Inheritance Basics49Public, Protected, and Private Inheritance50Types of Inheritance51Polymorphism52Function Overriding53Virtual Functions54Abstract Class and Pure Virtual Function
Tutorials/C++ Programming/Virtual Functions
⚡C++ Programming

Virtual Functions

Updated 2026-04-20
3 min read

Introduction

In object-oriented programming (OOP), polymorphism is a key concept that allows objects of different classes to be treated as objects of a common superclass. One of the primary mechanisms for achieving polymorphism in C++ is through the use of virtual functions. This tutorial will provide a comprehensive guide to understanding, implementing, and using virtual functions effectively in your C++ programs.

What are Virtual Functions?

A virtual function is a member function in a base class that you expect to override in derived classes. When you declare a function as virtual, you enable runtime polymorphism. The most common use of virtual functions is to allow a base class pointer or reference to call the appropriate overridden function in the derived class.

Key Characteristics

  • Dynamic Binding: Virtual functions are resolved at runtime, allowing for dynamic method binding.
  • Function Overriding: Derived classes can override the implementation of a virtual function provided by the base class.
  • Virtual Table (vtable): C++ uses a vtable to manage the addresses of virtual functions. Each class with virtual functions has its own vtable.

Declaring Virtual Functions

To declare a virtual function in a base class, use the virtual keyword before the function declaration. Here's an example:

class Animal {
public:
    // Declare a virtual function
    virtual void makeSound() const {
        std::cout << "Animal makes a sound" << std::endl;
    }
};

class Dog : public Animal {
public:
    // Override the base class function
    void makeSound() const override {
        std::cout << "Dog barks" << std::endl;
    }
};

Key Points

  • virtual Keyword: Indicates that the function can be overridden in derived classes.
  • override Keyword: (Optional but recommended) Used to indicate that a function is intended to override a base class function. It helps catch errors if the base class function signature changes.

Using Virtual Functions

Virtual functions are typically used when you have a collection of pointers or references to objects of different derived classes, and you want to call their specific versions of a function.

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

    // Calls the overridden version in Dog class
    animal1->makeSound();  // Output: Dog barks

    // Calls the base class version
    animal2->makeSound();  // Output: Animal makes a sound

    delete animal1;
    delete animal2;

    return 0;
}

Key Points

  • Polymorphic Behavior: The correct function is called based on the actual object type, not the pointer or reference type.
  • Memory Management: Ensure proper memory management with pointers to avoid memory leaks.

Pure Virtual Functions and Abstract Classes

A pure virtual function is a virtual function that has no implementation in the base class. It forces derived classes to provide their own implementations. A class containing at least one pure virtual function is called an abstract class and cannot be instantiated directly.

class Shape {
public:
    // Pure virtual function
    virtual void draw() const = 0;
};

class Circle : public Shape {
public:
    void draw() const override {
        std::cout << "Drawing a circle" << std::endl;
    }
};

Key Points

  • = 0 Syntax: Indicates a pure virtual function.
  • Abstract Classes: Cannot be instantiated and are used as interfaces.

Best Practices for Using Virtual Functions

  1. Minimize Overuse: Only use virtual functions when necessary to avoid unnecessary overhead.
  2. Use override Keyword: Always use the override keyword to ensure that you are actually overriding a base class function.
  3. Avoid Fragile Base Class Problem: Be cautious about modifying base classes, as it can affect derived classes if they rely on specific implementations.
  4. Prefer Interfaces Over Implementation: Use abstract classes to define interfaces and separate implementation details.

Real-World Example

Consider a simple graphics application where you have different shapes like circles, rectangles, and triangles. Each shape should be able to draw itself.

#include <iostream>

class Shape {
public:
    virtual void draw() const = 0;
    virtual ~Shape() {} // Virtual destructor for proper cleanup
};

class Circle : public Shape {
public:
    void draw() const override {
        std::cout << "Drawing a circle" << std::endl;
    }
};

class Rectangle : public Shape {
public:
    void draw() const override {
        std::cout << "Drawing a rectangle" << std::endl;
    }
};

class Triangle : public Shape {
public:
    void draw() const override {
        std::cout << "Drawing a triangle" << std::endl;
    }
};

int main() {
    Shape* shapes[] = {new Circle(), new Rectangle(), new Triangle()};

    for (const auto& shape : shapes) {
        shape->draw();
    }

    // Clean up
    for (auto& shape : shapes) {
        delete shape;
    }

    return 0;
}

Key Points

  • Encapsulation of Drawing Logic: Each shape class encapsulates its drawing logic.
  • Extensibility: Easy to add new shapes without modifying existing code.

Conclusion

Virtual functions are a powerful feature in C++ that enable polymorphism and dynamic method binding. By understanding how to declare, use, and manage virtual functions, you can write more flexible and maintainable object-oriented programs. Remember to follow best practices to ensure efficient and robust code.


This comprehensive guide should provide you with a solid foundation for using virtual functions in your C++ projects. Practice implementing these concepts in your own code to reinforce your understanding.


PreviousFunction OverridingNext Abstract Class and Pure Virtual Function

Recommended Gear

Function OverridingAbstract Class and Pure Virtual Function