1

Given this code:

class foo
{
public:
    foo() : _myFunc( bind( &foo::testCall, this ) ){}
    virtual void testCall(){ cout << "foo" << endl; }
    void call(){ _myFunc(); }
private:
    function< void() > _myFunc;
};

class bar: public foo
{
public:
    virtual void testCall(){ cout << "bar" << endl; }
};

void main()
{
    bar test;
    test.call();
}

Why does it print "bar". I read this issue and would have thought that "foo" would have been printed.

Community
  • 1
  • 1
Jonathan Mee
  • 37,899
  • 23
  • 129
  • 288

1 Answers1

1

You are not calling the virtual function in the constructor you are binding to a member variable, and latter calling that variable (in this case dynamic dispatch is used).

The calling code should be: test.call();

More info Boost::Bind and virtual function overloads: why do they work?

Community
  • 1
  • 1
NetVipeC
  • 4,402
  • 1
  • 17
  • 19
  • So I get what you are saying but in `foo`'s ctor I would have expected a hard coded address not one that would thunk. – Jonathan Mee Jul 17 '14 at 12:47
  • Link added with more explaining about the behavior. – NetVipeC Jul 17 '14 at 12:49
  • @JonathanMee its the address of a virtual member function, which is typically a base+offset into the virtual method table of the instance. By the time the object is fully constructed the member function address at that offset is `bar`'s – WhozCraig Jul 17 '14 at 12:50