W
WaterWalk
Hello. I thought I understood member function pointers, but in fact I
don't. Consider the following example:
class Base
{
public:
virtual ~Base() {}
};
class Derived : public Base
{
public:
void test()
{
printf("Derived::test()\n");
}
};
typedef void (Derived::*funcD) ();
typedef void (Base::*funcB) ();
int main()
{
funcD fd = &Derived::test;
funcB fb = static_cast<funcB>(fd);
Derived d;
Base *pb = &d;
(pb->*fb)(); // will print "Derived::test()" !
return 0;
}
To my surprise, this code works! However, if the Base class doesn't
have any virtual functions, the above code won't compile, or cause
runtime error. At the same time, in section 15.5.1 of BS's "The C++
Programming Language", it states that a pointer to base class member
can be assigned to a pointer to derived class member, but now vice
versa.
I'm lost. Please help me figure out how it works. And show me where in
the c++ standard allows this kind of usage, if you like. Thanks in
advance.
don't. Consider the following example:
class Base
{
public:
virtual ~Base() {}
};
class Derived : public Base
{
public:
void test()
{
printf("Derived::test()\n");
}
};
typedef void (Derived::*funcD) ();
typedef void (Base::*funcB) ();
int main()
{
funcD fd = &Derived::test;
funcB fb = static_cast<funcB>(fd);
Derived d;
Base *pb = &d;
(pb->*fb)(); // will print "Derived::test()" !
return 0;
}
To my surprise, this code works! However, if the Base class doesn't
have any virtual functions, the above code won't compile, or cause
runtime error. At the same time, in section 15.5.1 of BS's "The C++
Programming Language", it states that a pointer to base class member
can be assigned to a pointer to derived class member, but now vice
versa.
I'm lost. Please help me figure out how it works. And show me where in
the c++ standard allows this kind of usage, if you like. Thanks in
advance.