开发者

Does dynamic biding only happen with object on heap in C++?

开发者 https://www.devze.com 2022-12-27 00:56 出处:网络
Will dynamic binding happen with the object on stack? For example f() is a virtual function in both Base and Derived

Will dynamic binding happen with the object on stack?

For example

f() is a virtual function in both Base and Derived

开发者_如何学编程
int main(){

  Derived d1;
  Based *b= new Derived();

  d1.f();
  b->f();
}


Virtual functions work for both heap and stack objects. Try the following:

#include <iostream>

class base
{
public:
    virtual void doit()
    {
        std::cout << "base::doit" << std::endl;
    }
};

class derived : public base
{
public:
    virtual void doit()
    {
        std::cout << "derived::doit" << std::endl;
    }
};

void invokevirtual(base &b)
{
    b.doit();
}

int main()
{
    derived d;
    invokevirtual(d);
}


Yes.

Sorry for the short answer, but you seem to know what is happening and just needed some confirmation, right?

0

精彩评论

暂无评论...
验证码 换一张
取 消