It has been really hard for me to understand function pointers call with respect to member functions in the following example.
(f.*(FPTR) bp)(0); // This call b()
(b.*(BPTR) fp)(0); // This call f()
I would like to know the code replaced (as I know a function call like obj.Fun() is replaced by Fun(&obj) by the compiler for these two function calls when those member functions are virtual and non-virtual. Anyone help me to understand, Please ?
I want to understand more like this link explanation: http://www.learncpp.com/cpp-tutorial/8-8-the-hidden-this-pointer/
#include <iostream>
using std::cout;
using std::endl;
class Foo
{
public:
void f(int i = 0)
{
cout << "Foo" << endl;
}
};
class Bar
{
public:
void b(char c = 'b')
{
cout << "Bar" << endl;
}
};
int main()
{
typedef void (Foo::*FPTR) (int);
typedef void (Bar::*BPTR) (char);
FPTR fp = &Foo::f;
BPTR bp = &Bar::b;
Foo f;
Bar b;
/*
* we are casting pointer to non-compatible type here
* Code works, but want to know how it is.
*/
(f.*(FPTR) bp)(0);
(b.*(BPTR) fp)(0);
return 0;
}
Thanks
Your code displays undefined behaviour, which means that the compiler can do anything it likes, including what you (erroneously) expect it to do.