简体   繁体   中英

C++ Non-virtual function call in a virtual call

Why is the output of this program "CLASS A"? Isn't this determined to be of type B? Doesn't it mean that this->g() should call the B class's version of g?

#include <iostream>

using namespace std;

class A {
private:
    void g() {
        cout << "CLASS A" << endl;
    }
public:
    virtual void f() {
        g();
    }
};

class B : public A {
public:
    void g() {
        cout << "CLASS B" << endl;
    }
};

int main() {
    A* a = new B();
    a->f();
}

Isn't this determined to be of type B?

No. B may be the dynamic type, but the static type of *this is A within all its member functions.

The member function g is not virtual, so therefore a call to it uses static binding. In static binding, the dynamic type of the object is irrelevant - only the static type matters. A call to the non-virutal g within a member function of A should be a call to A::g .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM