views:

453

answers:

5

What is mean by delegates in c++, does sort function in c/c++ which takes a compare function/functor as last parameter is a form of delegate?

+2  A: 

Callback functions in C++ can be (loosely) referred as a form of delegates ( though delegate term is not used for this). The callback functions use Pointers to Functions to pass them as parameters to other functions. But delegates in C# is more advanced compared to callback functions in C++.

aJ
Callback functions is a C concept. Though it can be used in C++ it has been superseded by the concept of functors (objects that behave like functions).
Martin York
+2  A: 

Delegate: An object that acts like a multi-function pointer with a subscription system. It really simplifies the use of static or 'object' member function pointers for callback notifications and event handling.

This link explains Delegates in a lucid manner or you may also refer to the MSDN link.

Prasoon Saurav
+5  A: 

"delegate" is not really a part of the C++ terminology. In C# it's something like a glorified function pointer which can store the address of an object as well to invoke member functions. You can certainly write something like this in C++ as a small library feature. Or even more generic: Combine boost::bind<> with boost::function<>.

In C++ we use the term "function object". A function object is anything (including function pointers) that is "callable" via the function call operator().

std::sort takes a "predicate" which is a special function object that doesn't modify its arguments and returns a boolean value.

sellibitze
+1  A: 

To delegate work means to share the work load with others. In real life, if you were to delegate your task, ie if you are a manager, you would be sharing your work expecting others to complete a task without you having to know how.

The concept is the same in C++ and any other languages having the capability of delegates. In C you could see this as a delegate:

int calculate(int (*func)(int c), int a, int b)

Because you are expected to send a pointer, to another function which will compute some work for you. I recently wrote a blog post on function pointers in Python and C, check it out, you might find it helpfull. This might not be the "traditional" way to delegate work in C or C++, but then again, the termonoligy says i am a bit right.

Filip Ekberg
+1  A: 

Delegation is mostly used as a way to pass functions to functionality embedded in a class (pimpl, aggregation, private inheritance). They are mainly (inlined) functions of one line, calling functions of member-classes. As far as I know, it has nothing to do with C#'s delegates.

In this sense, a function-pointer as used in qsort is not a delegate, but a callback in which framework modules can be extended by user-software as in the Hollywood principle.

stefaanv