简体   繁体   中英

function call inside polymorphic call. virtual function call

The following is calling Derived::fn2() from Derived::fn1() , where as fn2() is not virtual so it should call Base class's function. Could anyone explain why?

#include <iostream>
using namespace std;

class Base{
    public:
    virtual void fn1()
    {
        cout<<"Base function 1"<<endl;
        this->fn2();
    }
    void fn2()
    {
        cout<<"Base function 2"<<endl;
    }
};


class Derived : public Base{
    public:
    
    void fn1()
    {
        cout<<"Derived function 1 "<<endl;
        this->fn2();
    }
    void fn2()
    {
        cout<<"Derived function 2"<<endl;
    }
};

int main()
{
    Base *b = new Derived();
    b->fn1();
}

fn2() is not virtual so it should call Base class's function.

No, it shouldn't. Here you are why:

Derived d;

static_cast<Base&>(d).fn1();
// Calls Derived::fn1 through dynamic dispatching. In Derived::fn1, `this` is
// of type Derived*, so it will call Derived::fn2

// Output:
// Derived function 1
// Derived function 2

static_cast<Base&>(d).fn2();
// fn2() is not virtual, so you overloaded it. You're calling Base::fn2().

// Output:
// Base function 2

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