views:

69

answers:

2

In Objective-C you can pass a method A as a parameter of other method B. and call method A from inside method B very easily like this:

-(void) setTarget:(id)object action:(SEL)selectorA
{
    if[object respondsToSelector:selectorA]{
       [object performSelector:selectorA withObject:nil afterDelay:0.0];
    }
}

Is there any functionally like this in C++ ?

+4  A: 

C++ and Objective-C are quite different in that regard.

Objective-C uses messaging to implement object method calling, which means that a method is resolved at run-time, allowing reflectivity and delegation.

C++ uses static typing, and V-tables to implement function calling in classes, meaning that functions are represented as pointers. It is not possible to dynamically determine whether a class implements a given method, because there are no method names in memory.

On the other hand, you can use RTTI to determine whether a given object belongs to a certain type.

void callFunc(generic_object * obj) {
    specific_object * spec_obj = dynamic_cast<specific_object*>(obj);
    if (spec_obj != NULL) {
        spec_obj->method();
    }
}

Edit:

As per nacho4d's demand, here is an example of dynamic invocation :

typedef void (specific_object::*ptr_to_func)();

void callFunc(generic_object * obj, ptr_to_func f) {
    specific_object * spec_obj = dynamic_cast<specific_object*>(obj);
    if (spec_obj != NULL) {
        ((*spec_obj).*f)();
    }
}
SirDarius
Thanks, If I can pass the method as a pointer, then can I call the passed method? I would appreciate an example of this, if possible
nacho4d
Thanks for the kind explanation and examples ;)
nacho4d
+2  A: 

Yes there is, and they are called "Function Pointers", you will get lots of results googling around,

http://www.newty.de/fpt/index.html

http://www.cprogramming.com/tutorial/function-pointers.html

Akash Kava
thanks, that seems a good place to start ;)
nacho4d