What does the 'virtual' keyword do in C++?

In C++, the virtual keyword is used to declare a virtual function, which allows for dynamic (or late) binding of function calls. This means that the function to be executed is determined at runtime based on the type of the object pointed to, rather than the type of the pointer.

Here are some key points about the virtual keyword:

  1. Polymorphism: It enables polymorphism, allowing derived classes to override base class methods.

  2. Base Class Pointer: When a base class pointer points to a derived class object, calling a virtual function will invoke the derived class's version of the function.

  3. Declaration: A virtual function is declared in the base class using the virtual keyword. For example:

    class Base {
    public:
        virtual void show() {
            std::cout << "Base class show function called." << std::endl;
        }
    };
  4. Overriding: In the derived class, you can override the virtual function:

    class Derived : public Base {
    public:
        void show() override { // 'override' is optional but recommended for clarity
            std::cout << "Derived class show function called." << std::endl;
        }
    };
  5. Destructor: If a class has virtual functions, it is a good practice to declare a virtual destructor to ensure proper cleanup of derived class objects.

Here’s a simple example demonstrating the use of the virtual keyword:

#include <iostream>
using namespace std;

class Base {
public:
    virtual void show() {
        cout << "Base class show function called." << endl;
    }
};

class Derived : public Base {
public:
    void show() override {
        cout << "Derived class show function called." << endl;
    }
};

int main() {
    Base* b;           // Base class pointer
    Derived d;        // Derived class object
    b = &d;           // Pointing to derived class object

    b->show();        // Calls Derived's show() due to virtual function
    return 0;
}

In this example, the output will be "Derived class show function called." because of the virtual function mechanism.

0 Comments

no data
Be the first to share your comment!