C++:当非重写调用重写方法时会发生什么?

Cod*_*rus 4 c++ overriding member-hiding

被调用的重写方法的版本取决于您是否关心“通过”基类或“通过”派生类调用函数。但是,我发现如果我调用一个非重写方法,并且重写方法调用一些重写的函数,那么基类版本仍然被调用,即使我通过指向派生类的指针访问实例。有人可以解释为什么会发生这种情况吗?

代码:

class Base {
public:
    void display() {
        foo();
    }
    void foo() {
        cout << "Base.foo()" << endl;
    }
};

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

int main() {
    Derived* derived = new Derived();
    derived->display();
    while (true) {}
}
Run Code Online (Sandbox Code Playgroud)

el.*_*ado 5

the base class version is still called, even though I am accessing the instance through pointer to the derived class. Could someone explain why this happens?

Although you call method via pointer to derived class, your method is not virtual, so static dispatch is used, so Base::display() calls Base::foo() directly, even if it is overridden in subclasses. To achieve behavior you want, you must use dynamic dispatch, i.e. mark your methods as virtual.

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

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

int main() {
    Derived* derived = new Derived();
    derived->display();
}
Run Code Online (Sandbox Code Playgroud)

Output:

Base.foo()
Derived.bar()
Run Code Online (Sandbox Code Playgroud)


小智 0

virtual qualifier needs to be used for methods that need to be overridden.
ex:
 class Base {
public:
    void display() {
        foo();
    }
    virtual void foo() {
        cout << "Base.foo()" << endl;
    }
};

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

int main() {
    Derived* derived = new Derived();
    derived->display();
    while (true) {}
}
Run Code Online (Sandbox Code Playgroud)