简体   繁体   中英

Binding Virtual Functions in Parent Ctor

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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