Introduction to C++ | Virtual Function

C++ Virtual Function

A virtual function in C++ is a member function in a base class that you can override in a derived class. When a virtual function is called through a base class reference or pointer, the function in the derived class is executed if it is overridden. This enables runtime polymorphism.

What is a Virtual Function?

A virtual function allows dynamic (runtime) dispatch of function calls based on the actual type of the object being referred to, rather than the type of the pointer or reference.

Syntax of a Virtual Function

Syntax


        class Base {
        public:
            virtual returnType functionName(parameters) {
                // Base class implementation
            }
        };
        
        class Derived : public Base {
        public:
            returnType functionName(parameters) override {
                // Derived class implementation
            }
        };
                    

Key Points About Virtual Functions

Example of Virtual Functions

Here’s an example demonstrating the use of virtual functions:

Code Example


        #include <iostream>
        using namespace std;
        
        class Base {
        public:
            virtual void display() {
                cout << "Display from Base Class" << endl;
            }
        };
        
        class Derived : public Base {
        public:
            void display() override {
                cout << "Display from Derived Class" << endl;
            }
        };
        
        int main() {
            Base* basePtr;
            Derived derivedObj;
        
            basePtr = &derivedObj;
        
            // Calls the overridden function in Derived class
            basePtr->display();
        
            return 0;
        }
                    

Output

Display from Derived Class

Rules for Virtual Functions

Pure Virtual Functions and Abstract Classes

A pure virtual function is a virtual function that is declared by assigning 0 in the base class. Classes containing pure virtual functions are called abstract classes and cannot be instantiated.

Syntax:

Syntax for Pure Virtual Function


        class AbstractBase {
        public:
            virtual void pureVirtualFunction() = 0;  // Pure virtual function
        };
                    

Common Mistakes with Virtual Functions

Pro Tip:

💡 Pro Tip

Always declare destructors as virtual in base classes when using inheritance. This ensures that derived class destructors are called correctly, avoiding potential resource leaks.