When calling a subclass in C++, if the subclass does not have a corresponding function, will the parent class be automatically called?

In C++, if the subclass does not have a corresponding function (that is, the subclass does not override the function of the parent class), and you try to call the function on the subclass object, C++ will not automatically call the function of the parent class. Instead, it throws a compilation error or a runtime error, depending on the situation.

Here's an example illustrating this situation:

#include <iostream>

class ParentClass {
    
    
public:
    void showMessage() {
    
    
        std::cout << "ParentClass message" << std::endl;
    }
};

class ChildClass : public ParentClass {
    
    
    // 子类没有对 showMessage() 函数进行重写
};

int main() {
    
    
    ChildClass childObj;
    childObj.showMessage(); // 这将调用父类的 showMessage() 函数
    return 0;
}

In the above example, ChildClassinheritance is inherited ParentClass, but showMessage()the function is not overridden. When we create ChildClassan object and call showMessage()a method, it automatically calls showMessage()the method of the parent class.

If you want a subclass to override a method of the parent class, you need to explicitly override the method in the subclass, using the overridekeyword to ensure correct override. If not rewritten correctly, the C++ compiler will usually issue a warning or error.

class ChildClass : public ParentClass {
    
    
public:
    void showMessage() override {
    
    
        std::cout << "ChildClass message" << std::endl;
    }
};

In this case, when you ChildClasscall showMessage()a method on the object, it will call the overridden version of the child class instead of the parent class's version.

Guess you like

Origin blog.csdn.net/qq_42244167/article/details/132534820