7 years, 12 months ago.

Virtual Pointer to Member Function and Ticker

When attaching a virtual pointer to member function (PMF) to a ticker in a base class, the ticker callback does not call the function on the derived class. Instead, it calls the function on the base class, even if it is a pure virtual function.

A code example would be helpful here, also see http://stackoverflow.com/questions/4658627/virtual-pointer for how there isn't such a thing as a "virtual pointer"

Further to the above according to http://www.codeguru.com/cpp/cpp/article.php/c17401/C-Tutorial-PointertoMember-Function.htm it should point to the function in the derived class so if you are right you have hit on non-standard behavior. Correction: I'm still trying to work out what they actually mean.

I'd like to see an example demonstrating this.

posted by Oliver Broad 07 May 2016

Hi Jonathan, please provide an example to illustrate the point

posted by Martin Kojtal 09 May 2016

1 Answer

7 years, 12 months ago.

Not an authority on this but I'm trying because I thought there was a simple answer but the more I looked the deeper it got. I think the best thing to do might be to make the question more abstract and re-post it on a site like stackoverflow...

As I understand it it is the type/class of the object passed to the ticker that determines which class's member function gets called, and I presume you are passing "this", so it is the class of "this" which determines the function to be called. In the context of a member function "this" is the class the member function belongs to, not the derived class.

I had presumed that the function pointer would just contain a pointer to the actual implementation of the function like it would with a regular function, and that the only difference would be the implicit "this" parameter passed to the function. I was so wrong there. It is more like an index into the virtual method table, so when the pointer is invoked on an object it takes the class of the object. Even that isn't quite right as the function pointer could just as easily be pointed to a non-virtual function.

To elaborate further: the callback class used by ticker uses templating, and I think that the template gets resolved at compile time not run time and I'm guessing that means the class gets "baked in" at that point. Although the more I think about it the more I think that "this" is still a pointer so overrides should still apply?

The net result is it looks like a non-virtual function call, but that's just because you can't override the type of object passed to the ticker.