Pointer to member function of derived class, but not derived(virtual) function

256 views Asked by At

I have a particular problem I want to solve, I'm not sure if it's possible as I can't find any information or examples of it being done. Basically, I have:

class ParentObject {};

class DerivedObject : public ParentObject
{
    void myFunction(){}
};

class OtherDerivedObject : public ParentObject
{
   void myOtherFunction(){}
};

and want a function pointer to ParentObject::* and have it able to take functions from either derived class. My reason for wanting to do so, I have another class

class functionRegistry
{
  std::map<string, *functionPoint> functionMap;
}

and each object (ideally in ParentObject but can do individually in the derived objects if necessary) have an instance of a functionRegistry, and I need functionPoint to be able to point to functions in objects of either type DerivedObject or OtherDerivedObject.

Thanks in advance

1

There are 1 answers

5
StoryTeller - Unslander Monica On BEST ANSWER

All you need is a static_cast to populate the map with the correct type.

using pfunc_type = void (ParentObject::*)() ;
pfunc_type pfunc1 = static_cast<pfunc_type>(&DerivedObject::myFunction);

As this is allowed by the standard:

[expr.static.cast/12] - §5.2.9¶12

A prvalue of type “pointer to member of D of type cv1 T” can be converted to a prvalue of type “pointer to member of B of type cv2 T”, where B is a base class (Clause [class.derived]) of D, if cv2 is the same cv-qualification as, or greater cv-qualification than, cv1.72 If no valid standard conversion from “pointer to member of B of type T” to “pointer to member of D of type T” exists ([conv.mem]), the program is ill-formed. The null member pointer value ([conv.mem]) 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 behavior is undefined. [ Note: although class B need not contain the original member, the dynamic type of the object with which indirection through the pointer to member is performed must contain the original member; see [expr.mptr.oper]. — end note ]

But while this is allowed, you must be very careful to make sure you apply the pointer to member on an object with the correct dynamic type.