How to use the virtual keyword in C++?

In C++, the virtual keyword is used to declare a virtual function. A virtual function is a function declared in a base class that can be redefined in a derived class. When calling this function using a base class pointer or reference, the function called will be determined based on the actual type of the object, whether it is the virtual function in the base class or the redefined function in the derived class.

The usage instructions are as follows:

  1. Declare a virtual function in the base class.
class Base {
public:
    virtual void foo() {
        // 基类中的虚函数定义
    }
};
  1. Override virtual functions in derived classes.
class Derived : public Base {
public:
    void foo() override {
        // 派生类中的重新定义的函数
    }
};

After C++11, the override keyword can be used to explicitly mark virtual functions in derived classes, enhancing code readability and maintainability.

  1. Call a virtual function using a base class pointer or reference.
Base* ptr = new Derived();
ptr->foo();   // 调用派生类中重新定义的虚函数

In the above example, when a base class pointer ptr points to a derived class object, calling ptr->foo() will determine whether to call the virtual function in the base class or the redefined function in the derived class based on the actual type of the object.

bannerAds