Binding to a virtual function from a parent class.

Hey guys... I have a situation where I'm not sure on the standard behavior. I was hoping I could get some feedback from someone who knows:

Consider the below situation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <functional>
#include <iomanip>
using namespace std;

typedef function<void()>    func;

func f;


class Parent
{
public:
    Parent()
    {
        f = std::bind(&Parent::callMe,this);

        f();
    }

    virtual void callMe()
    {
        cout << "parent" << endl;
    }
};

class Child : public Parent
{
    virtual void callMe()
    {
        cout << "child" << endl;
    }
};



int main ()
{
    Child c;

    f();
}
parent
child



The output above is how it behaves in VS2012. This is the behavior I would expect. I desire/expect the below behavior:

- f can legally bound to 'callMe', even in the Parent's ctor
- The function is treated as virtual even when called through the function pointer. So the child class's override is called once Child has been constructed.


My question is... is this standard behavior? Is this how this will work everywhere? Or am I doing something undefined?

Thanks
Last edited on
Topic archived. No new replies allowed.