How can I call the C++ override method?

In C++, the override keyword can be used to explicitly indicate that a function is overriding a virtual function in a base class. The syntax for using the override keyword is as follows:

class Base {
public:
    virtual void foo() const {
        cout << "Base::foo()" << endl;
    }
};

class Derived : public Base {
public:
    void foo() const override {
        cout << "Derived::foo()" << endl;
    }
};

int main() {
    Derived d;
    d.foo(); // 调用Derived类中的foo()函数
    return 0;
}

In the above example code, the Derived class inherits from the Base class and overrides the virtual function foo(). Using the override keyword to modify the foo() function in the Derived class allows the compiler to verify if this function truly overrides the virtual function in the base class.

In the main function, we created an object of the Derived class named ‘d’ and called its foo() function. Because the foo() function is marked as override, the compiler automatically calls the foo() function in the Derived class, resulting in the output “Derived::foo()”.

bannerAds