tags:

views:

73

answers:

2

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();
}
+6  A: 

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);
}
R Samuel Klatchko
so you what's the output? I have no compiler right now. I can't see. If the output is "derived::doit", that's what you mean dynamic binding?
skydoor
@skydoor - the output is "derived::doit" because virtual functions work for all objects regardless of where they are allocated.
R Samuel Klatchko
A: 

Yes.

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

Spidey