Does dynamic biding only happen with object on heap in C++?
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?
精彩评论