简体   繁体   English

从正常函数调用虚函数

[英]Virtual function call from a normal function

class base
{
public:
    void virtual func(){cout<<"base";}
    void check()
    {
        func();
    }
};
class derived: public base
{
public:
    void func(){cout<<"dervied";}
};
int main()
{
    base *obj = new derived();
    obj->check();
    return 0;
}

Above code prints derived on the console. 以上代码打印在控制台上派生。 Now, I understand the concept of virtual functions but I'm unable to apply it here. 现在,我理解虚函数的概念,但我无法在此处应用它。 In my understanding whenever we call a virtual function, compiler modifies the call to "this->vptr->virtualfunc()" and that's how most heavily derived's class function gets invoked. 根据我的理解,每当我们调用虚函数时,编译器都会修改对"this->vptr->virtualfunc()"的调用,这就是调用最多派生类函数的方式。 But in this case, since check() is not a virtual function, how does the compiler determine that it needs to invoke func() of derived? 但在这种情况下,由于check()不是虚函数,编译器如何确定它需要调用派生的func()

how does the compiler determine that it needs to invoke func() of derived? 编译器如何确定它需要调用派生的func()?

In the same exat way - by invoking this->vptr->virtualfunc() . 以相同的exat方式 - 通过调用this->vptr->virtualfunc() Recall that this belongs to the derived class even inside the base class, because each derived class is a base class as well, so the same way of accessing virtual functions works for it too. 回想一下,即使在基类内部, this属于派生类,因为每个派生类也是基类,因此访问虚函数的方式也适用于它。

Exactly the way you said, by using the vptr in the class member. vptr你所说的那样,通过在类成员中使用vptr It knows the function is virtual , therefore it knows it has to call it through the virtual function table. 它知道函数是virtual函数,因此它知道它必须通过虚函数表调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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