473,605 Members | 2,136 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Member function pointer cast question

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::*func D) ();
typedef void (Base::*funcB) ();

int main()
{
funcD fd = &Derived::te st;
funcB fb = static_cast<fun cB>(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.

Sep 25 '07 #1
7 3795
WaterWalk wrote:
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::*func D) ();
typedef void (Base::*funcB) ();

int main()
{
funcD fd = &Derived::te st;
funcB fb = static_cast<fun cB>(fd);
Don't have my copy of the Standard handy, but I believe this cast leads
to UB.
Derived d;
Base *pb = &d;
(pb->*fb)(); // will print "Derived::test( )" !
return 0;
}

To my surprise, this code works!
UB can do anything, including working "as expected".

Sep 25 '07 #2
"WaterWalk" <to********@163 .comwrote in message
news:11******** *************@2 2g2000hsm.googl egroups.com...
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::*func D) ();
typedef void (Base::*funcB) ();

int main()
{
funcD fd = &Derived::te st;
funcB fb = static_cast<fun cB>(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.
It's undefined behavior. I understand why it works, but it's not guaranteed
to work in all implementations . And next version of the compiler, it may
not work anymore.
Sep 25 '07 #3
On Sep 25, 1:13 pm, WaterWalk <toolmas...@163 .comwrote:
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::*func D) ();
typedef void (Base::*funcB) ();

int main()
{
funcD fd = &Derived::te st;
funcB fb = static_cast<fun cB>(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.
I made a mistake. Base needn't to have virtual functions to make the
code "work".

Sep 25 '07 #4
On Sep 25, 1:13 pm, WaterWalk <toolmas...@163 .comwrote:
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::*func D) ();
typedef void (Base::*funcB) ();

int main()
{
funcD fd = &Derived::te st;
funcB fb = static_cast<fun cB>(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.
It seems that this "technology " is useful. When I browse the wxWidgets
source code, I find it's event mechanism may use pointer-to-member-
function this way. When it needs to register an event handler, it'll
cast the member function pointer to base member function pointer,
store it somewhere, and later call it.

So I wonder whether this is undefined behavior. If it is, then
wxWidgets may be built on a weak base.(Maybe I am wrong here.)

Sep 25 '07 #5
On Sep 25, 7:13 am, WaterWalk <toolmas...@163 .comwrote:
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::*func D) ();
typedef void (Base::*funcB) ();
int main()
{
funcD fd = &Derived::te st;
funcB fb = static_cast<fun cB>(fd);
Derived d;
Base *pb = &d;
(pb->*fb)(); // will print "Derived::test( )" !
return 0;
}
To my surprise, this code works!
It's guaranteed by the standard. At least one major GUI
framework used something like this for its callbacks. (But it
surprised me as well when I first encountered it, and I had to
verify in the standard that it was well defined.)
However, if the Base class doesn't have any virtual functions,
the above code won't compile, or cause runtime error.
It should work, regardless. At least one major compiler (VC++),
however, uses a broken implementation of pointers to member functions
by
default; if you're using VC++, you probably need the /vmg option.
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 not vice versa.
There's an implicit conversion of Derived::* to Base::*. You
need a static_cast to go the other direction, and when using the
resulting Base::*, it's undefined behavior unless the Base
object is actually a Derived.
I'm lost. Please help me figure out how it works.
How it works is the implementors problem. Normally, a pointer
to member function will be a struct with quite a bit of
information: whether the function is virtual or not, the actual
address of the function, if it's not, or its index in the
vtable, if it is, any offset or correction needed for the this
pointer, etc. And calling through a pointer to member involves
evaluating all this information. Alterantively, an
implementation may use a "trampoline "; when you take the address
of a pointer to member, it creates a small function which does
whatever is necessary to call the function, given the address of
the object. And conversions like the above involve modifying
the information or generating a new trampoline.
And show me where in the c++ standard allows this kind of
usage.
§5.2.9/10:

An rvalue of type "pointer to member of D of type cv1 T"
can be converted to an rvalue of type "pointer to member
of B" of type cv2 T, where B is a base class (clause 10)
of D, if a valid standard conversion from "pointer to
member of B of type T" to "pointer to member of D of
type T" exists (4.11), and cv2 is the same
cv-qualification as, or greater cv-qualification than,
cv1.69) The null member pointer value (4.11) is
converted to the null member pointer value of the
destination type. If class B contains the original
member, or is a base or derived class of the class
containing the original member, the resulting pointer to
member points to the original member. Otherwise, the
result of the cast is undefined. [ Note: although class
B need not contain the original member, the dynamic type
of the object on which the pointer to member is
dereferenced must contain the original member; see 5.5.
--end note ]

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Sep 25 '07 #6
On 2007-09-25 06:11:35 -0400, James Kanze <ja*********@gm ail.comsaid:
>
There's an implicit conversion of Derived::* to Base::*.
Typo. That should be: There's an implicit conversion of Base::* to
Derived::*. It goes the opposite way from ordinary pointer conversions.
You
need a static_cast to go the other direction, and when using the
resulting Base::*, it's undefined behavior unless the Base
object is actually a Derived.
--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)

Sep 25 '07 #7
On Sep 25, 6:11 pm, James Kanze <james.ka...@gm ail.comwrote:
On Sep 25, 7:13 am, WaterWalk <toolmas...@163 .comwrote:
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::*func D) ();
typedef void (Base::*funcB) ();
int main()
{
funcD fd = &Derived::te st;
funcB fb = static_cast<fun cB>(fd);
Derived d;
Base *pb = &d;
(pb->*fb)(); // will print "Derived::test( )" !
return 0;
}
To my surprise, this code works!

It's guaranteed by the standard. At least one major GUI
framework used something like this for its callbacks. (But it
surprised me as well when I first encountered it, and I had to
verify in the standard that it was well defined.)
However, if the Base class doesn't have any virtual functions,
the above code won't compile, or cause runtime error.

It should work, regardless. At least one major compiler (VC++),
however, uses a broken implementation of pointers to member functions
by
default; if you're using VC++, you probably need the /vmg option.
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 not vice versa.

There's an implicit conversion of Derived::* to Base::*. You
need a static_cast to go the other direction, and when using the
resulting Base::*, it's undefined behavior unless the Base
object is actually a Derived.
I'm lost. Please help me figure out how it works.

How it works is the implementors problem. Normally, a pointer
to member function will be a struct with quite a bit of
information: whether the function is virtual or not, the actual
address of the function, if it's not, or its index in the
vtable, if it is, any offset or correction needed for the this
pointer, etc. And calling through a pointer to member involves
evaluating all this information. Alterantively, an
implementation may use a "trampoline "; when you take the address
of a pointer to member, it creates a small function which does
whatever is necessary to call the function, given the address of
the object. And conversions like the above involve modifying
the information or generating a new trampoline.
And show me where in the c++ standard allows this kind of
usage.

§5.2.9/10:

An rvalue of type "pointer to member of D of type cv1 T"
can be converted to an rvalue of type "pointer to member
of B" of type cv2 T, where B is a base class (clause 10)
of D, if a valid standard conversion from "pointer to
member of B of type T" to "pointer to member of D of
type T" exists (4.11), and cv2 is the same
cv-qualification as, or greater cv-qualification than,
cv1.69) The null member pointer value (4.11) is
converted to the null member pointer value of the
destination type. If class B contains the original
member, or is a base or derived class of the class
containing the original member, the resulting pointer to
member points to the original member. Otherwise, the
result of the cast is undefined. [ Note: although class
B need not contain the original member, the dynamic type
of the object on which the pointer to member is
dereferenced must contain the original member; see 5.5.
--end note ]

--
James Kanze (GABI Software) email:james.ka. ..@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Thanks. That makes all clear.

Sep 26 '07 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
12195
by: Bren | last post by:
Hi all, Given this situation: class Base { typedef void (Base::*FN_FOO)(); virtual void Foo() = 0; // pure virtual void GetFoo(FN_FOO pfnFoo) = 0; // pure virtual
37
4979
by: Ben | last post by:
Hi, there. Recently I was working on a problem where we want to save generic closures in a data structure (a vector). The closure should work for any data type and any method with pre-defined signature. When developing this lib, I figured that the pointer-to-member-function, although seemingly an attractive solution, does not work well for us.
15
3477
by: Albert | last post by:
Hi, I need to pass a pointer-to-member-function as a parameter to a function which takes pointer-to-function as an argument. Is there any way to do it besides overloading the function? Here is a small program I wrote to check if I could get the address of the function from the member-function-pointer, so that I could pass it to the function as a normal function-pointer.
1
1664
by: none | last post by:
Hi, I have a base class with a pointer-to-member function variable. Then I have a derived class that needs to use that variable to call a member function (with the same arguments and return value type) in the derived class. I know in Visual C++ you can just cast the pointer to member function of the derived class to that of the base class and it will work, but is this legal by C++ standards?
2
1533
by: trying_to_learn | last post by:
im trying to index through an array that is member of a class using ptr to member in main i tried making a ptr to the member 'arr' : const int * testclass7::* ptrToMemberIntPtr = &testclass7::arr; ------------------------------------------------------ the compiler cries: cannot convert from 'int (testclass7::*)' to 'const int *testclass7::* ' Types pointed to are unrelated; conversion requires reinterpret_cast,
8
5651
by: wkaras | last post by:
In my compiler, the following code generates an error: union U { int i; double d; }; U u; int *ip = &u.i; U *up = static_cast<U *>(ip); // error I have to change the cast to reinterpret_cast for the code
4
1424
by: Egbert Nierop \(MVP for IIS\) | last post by:
Hi, I have a CWindowImpl derived class , see below at ***, that needs to subclass simple controls like textboxes. like this...: m_MyControl.SubclassWindow(GetDlgItem(IDC_MyControl).m_hWnd); ==> problem here m_MyControl.SetMouseHover(
3
2607
by: dice | last post by:
Hi, In order to use an external api call that requires a function pointer I am currently creating static wrappers to call my objects functions. I want to re-jig this so I only need 1 static wrapper function. I would prefer to be able to pass the member function as a void* to the static wrapper but I suspect this may not even be possible. Another solution would be option 2 below but I can't figure out the syntax to call obj->*pFn(). ...
13
2515
by: JohnQ | last post by:
The implementation of classes with virtual functions is conceptually easy to understand: they use vtables. Which begs the question about POD structs: how are they associated with their member functions in common implementations? And where is the 'this' ptr tucked away at for POD structs with member functions? John
0
8428
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8423
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8076
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8290
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
5889
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5446
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3913
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
3960
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1274
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.