In how many ways can a function be invoked(called) in C++? - c++

I know of one way to call a function :
func(x, y);
Are there more ways to call a function?

Functions can be invoked
explicitly, by providing an argument parenthesis after a designation of the function (in the case of constructors this is decidedly not formally correct wording, since they don't have names, but anyway),
implicitly, in particular destructors and default constructors, but also implicit type conversion,
via operators other than the function call operator (), in particular the copy assignment operator = and the dereferencing operator ->,
in a placement new expression, invocation of a specified allocation function by placing an argument parenthesis right after new (not sure if this counts as a separate way).
In addition library facilities can of course invoke functions for you.
I think the above list is exhaustive, but I'm not sure. I remember Andrei Alexandrescu enumerated the constructs that yielded callable thingies, in his Modern C++ Design book, and there was a surprise for me. So there is a possibility that the above is not exhaustive.

Arbitrary functions can be invoked:
using f(arguments...) notation
via a pointer to the function (whether member or non-)
via a std::function - (will check the implementation's left unspecified, though I'd expect it to use a pointer to function or pointer to member function under the covers so no new language features)
Class-specific functions are also invoked in certain situations:
constructors are invoked when objects are created on the stack, and when static/global or thread-specific objects or dynamically-allocated objects are dynamically initialised, or with placement new, and as expressions are evaluated
destructors are invoked when objects leave scope, are deleted, threads exit, temporaries are destroyed, and when the destructor is explicitly called ala x.~X()
all manner of operators ([], +=, ==, < etc.) may be invoked during expression evaluation
Arbitrary non-member functions may be run by:
functions may be run due to earlier std::atexit() or std::at_quick_exit() calls, and if they throw std::terminate may run
thread creation and asynchronous signals (again the interfaces accept pointer to functions, and there's no reason to think any implementation has or would use any other technique to achieve dispatch)
Specific functions are triggered in very specific situations:
main() is executed by the runtime
std::unexpected, std::unexpected_handler, std::terminate are invoked when dynamic exception specifications are violated
It's also possible to use setjmp and longjmp to "jump" back into a function... not quite the same thing as calling it though.
Though not truly "C++", it's also possible to arrange function execution using inline assembly language / linked assembler, writing to executable memory.

C++ is a fairly flexible language and therefore this is a very vague question as there can be a 100 different ways of "calling a function" given not limitations of what is allowed.
Remember a function is only really a block of code sitting somewhere in memory. The act of "calling" a function is to some extent the following:
Putting the parameters required in the correct registers/stack locations
Moving the PC(Program Counter) to the location of the function in memory (this is usually done with a "call" type machine instruction)
Technically afterwards there might be some "clean-up" code depending on how the compiler implements functions.
In the end all methods come down to this happening in some way or another.
Perhaps not 100% relevant here but remember that in C++ functions can be members of a class.
class MyClass{
public:
void myFunction(int A);
}
Usually what happens in this case is that the class object is passed as a first parameters.
So the function call:
myObject.myFunction(A)
is in a way equivalent to calling:
myFunction(myObject,A)
if you look at function object you will see this kind of behavior.
Function objects reference
Ok so here is a short list:
call the function normally myFunc(a,b);
function pointers. typedef int(*funcP)(int,in);
Function objects. overload the () operator makes your object callable.
C++11 std::function replaces function pointers largely and I suggest you look into how these works
lambda functions are also a type of function in a way.
Delegates can have a variety of implementations.
Things like function pointers and delegates are many times used with the concept of a callback
You can use multi-cast delegates. (e.g. boost.signals2 or Qt Signals & slots)
You can bind to a function in a DLL and call it. DLL calling
There are various ways to call functions between processes and over the network. Usually refereed to as rpc implementations.
In a threaded environment things might also get more interesting as you might want to call functions in a different thread.
See Qt Signals & Slots threaded connections
Also thread pools can be used. link1 link2
Lastly I suppose it's a good idea to mention meta-programming and the idea of RTTI. This is not as strongly supported as say in languages like c#.
If this is to be manually implemented one would be able to at run-time search the list of available functions and call one. By this method it would be possible to match a function at run-time vs a string name. This is to some extent impemented by Qt's MOC system.

What are we counting as a different way? If I have a function that is a member of a class foo, then I might call it like this:
foo.func(x, y);
If I have a pointer to foo, I would do this
foo->func(x, y);
If I had a class bar that was derived from foo, I might call foo's constructor with an initialization list
bar::bar(const int x, const int y) : foo(x, y) {}
A constructor is just a function, after all.

Related

C++ argument of type is incompatible with parameter of type void (__cdecl*)(void), when calling std::atexit()

While using certain C++ libraries, I've often come across functions with parameters requiring pointers to functions. This implies methods won't be accepted.
Such as std's atexit(void (__cdecl*)(void));
In this case, it's very inconvenient to call such function from a class, when you'd like to pass the functionality from a method.
I know of these two workarounds, but they have drawbacks/seem impossible:
Declaring the method as static: Means that method can't call any
other non-static methods from the same class.
Passing an actual function: Is an absolute mess, and may require all
sorts of black magic to get the propper functionality to execute
within the method.
What other workarounds are there for these situations in general? Or at least for calling the atexit() example from a class where a method would be ideal as exit function.
atexit functions are called on program exit, in reverse order. Local static object destructors are also called at this point. So in this example:
void f()
{
static X x;
atexit(f1);
static Y y;
}
On first call x and y destructor would be registered to be called on program exit, and f1() would be called between y.Y::~Y() and x.X::~X().
So if you create a collection of std::function objects to be called on destruction of the collection, that may be a viable workaround.
It still may not work well for multiple functions, as all would be called in a single loop, instead of LIFO order relative to other static destructor / atexit call.
Another option could be to look at at_thread_exit. It has different semantic, but may suit your needs as well.
Thunk, mentioned by #Remy Lebeau, could be the best workaround. But it may be nontrivial to implement, that's why I suggest considering other workarounds as well.

Is there a reason some functions don't take a void*?

Many functions accept a function pointer as an argument. atexit and call_once are excellent examples. If these higher level functions accepted a void* argument, such as atexit(&myFunction, &argumentForMyFunction), then I could easily wrap any functor I pleased by passing a function pointer and a block of data to provide statefulness.
As is, there are many cases where I wish I could register a callback with arguments, but the registration function does not allow me to pass any arguments through. atexit only accepts one argument: a function taking 0 arguments. I cannot register a function to clean up after my object, I must register a function which cleans up after all objects of a class, and force my class to maintain a list of all objects needing cleanup.
I always viewed this as an oversight, there seemed no valid reason why you wouldn't allow a measly 4 or 8 byte pointer to be passed along, unless you were on an extremely limited microcontroller. I always assumed they simply didn't realize how important that extra argument could be until it was too late to redefine the spec. In the case of call_once, the posix version accepts no arguments, but the C++11 version accepts a functor (which is virtually equivalent to passing a function and an argument, only the compiler does some of the work for you).
Is there any reason why one would choose not to allow that extra argument? Is there an advantage to accepting only "void functions with 0 arguments"?
I think atexit is just a special case, because whatever function you pass to it is supposed to be called only once. Therefore whatever state it needs to do its job can just be kept in global variables. If atexit were being designed today, it would probably take a void* in order to enable you to avoid using global variables, but that wouldn't actually give it any new functionality; it would just make the code slightly cleaner in some cases.
For many APIs, though, callbacks are allowed to take additional arguments, and not allowing them to do so would be a severe design flaw. For example, pthread_create does let you pass a void*, which makes sense because otherwise you'd need a separate function for each thread, and it would be totally impossible to write a program that spawns a variable number of threads.
Quite a number of the interfaces taking function pointers lacking a pass-through argument are simply coming from a different time. However, their signatures can't be changed without breaking existing code. It is sort of a misdesign but that's easy to say in hindsight. The overall programming style has moved on to have limited uses of functional programming within generally non-functional programming languages. Also, at the time many of these interfaces were created storing any extra data even on "normal" computers implied an observable extra cost: aside from the extra storage used, the extra argument also needs to be passed even when it isn't used. Sure, atexit() is hardly bound to be a performance bottleneck seeing that it is called just once but if you'd pass an extra pointer everywhere you'd surely also have one qsort()'s comparison function.
Specifically for something like atexit() it is reasonably straight forward to use a custom global object with which function objects to be invoked upon exit are registered: just register a function with atexit() calling all of the functions registered with said global object. Also note that atexit() is only guaranteed to register up to 32 functions although implementations may support more registered functions. It seems ill-advised to use it as a registry for object clean-up function rather than the function which calling an object clean-up function as other libraries may have a need to register functions, too.
That said, I can't imagine why atexit() is particular useful in C++ where objects are automatically destroyed upon program termination anyway. Of course, this approach assumes that all objects are somehow held but that's normally necessary anyway in some form or the other and typically done using appropriate RAII objects.

Why the delegates or closures often referred as true "object-oriented function pointers"?

For example, considering the C#
Unlike function pointers in C or C++, delegates are object-oriented,
type-safe, and secure.
source:
http://msdn.microsoft.com/en-us/library/aa288459%28v=vs.71%29.aspx
Now talking about the C++ only, what is the real difference and what is missing from an OO prospective?
Also from another source
Most C++ programmers have never used member function pointers, and
with good reason. They have their own bizarre syntax (the ->* and .*
operators, for example), it's hard to find accurate information about
them, and most of the things you can do with them could be done better
in some other way. This is a bit scandalous: it's actually easier for
a compiler writer to implement proper delegates than it is to
implement member function pointers!
source:
http://www.codeproject.com/Articles/7150/Member-Function-Pointers-and-the-Fastest-Possible
I find that many programs in C++ uses the ->* syntax, i don't find that this is bizarre or strange; I don't get the point about this potential about the delegates and the attack to the pointers.
The difference between a member pointer and a true closure is that a closure contains the function and the associated state. The two are inseparable.
A member pointer is just the function. In order to call a member pointer, you must provide the state.
It's the difference between a function pointer and a functor. The function object holds the function to be called (as an overload of operator()), but it can also have members. Those members can be private, thus providing encapsulation. The function object is an object by C++ rules, so it has an explicit lifetime. It is constructed and destructed according to C++ rules.
A function pointer has no lifetime; it always exists (unless it's NULL). It has no state to encapsulate.
Therefore, it's not a closure because it can't close over anything.
That's why C++11 lambdas are implemented as explicit objects. That way, they can close over things. They have encapsulated state.
I think people find it difficult to write them, but they behave like ordinary pointers, if they are NULL then its wrong to execute them. If they are written and used properly then there is nothing wrong with them. I never really had problems with,maybe besides forgetting proper syntax.
In c++11, you can use std::function<> class which is a wrapper for function pointer. You can use it for functions, member functions, functions objects and lambdas.
for example:
void foo(int x);
std::function<void(int)> f=foo;
f(1);
or easier (works in VS2010):
void foo(int x);
std::function<decltype(foo)> f=foo;
f(1);
ref: http://en.cppreference.com/w/cpp/utility/functional/function
Member function pointers are not member functions. Function pointers in C/C++ are dangerous in the sense that they could point to deallocated memory or be set to NULL at any time. Generally they are avoided, though not always with things like boost::bind or swapping print functions.
Thus in general they aren't any more dangerous than standard pointers. However, you can oftentimes avoid using function pointers by just calling an object's member method or a static function somewhere else. It compiles to using function pointers on the inside, but you have better guarantees about the existence of that function when it gets called.

STL Functional -- Why?

In C++ Standard Template Library, there's a 'functional' part, in which many classes have overloaded their () operator.
Does it bring any convenience to use functions as objects in C++?
Why can't we just use function pointer instead? Any examples?
Ofcourse, One can always use Function pointers instead of Function Objects, However there are certain advantages which function objects provide over function pointers, namely:
Better Performance:
One of the most distinct and important advantage is they are more likely to yield better performance. In case of function objects more details are available at compile time so that the compiler can accurately determine and hence inline the function to be called unlike in case of function pointers where the derefencing of the pointer makes it difficult for the compiler to determine the actual function that will be called.
Function objects are Smart functions:
Function objects may have other member functions and attributes.This means that function objects have a state. In fact, the same function, represented by a function object, may have different states at the same time. This is not possible for ordinary functions. Another advantage of function objects is that you can initialize them at runtime before you use/call them.
Power of Generic programming:
Ordinary functions can have different types only when their signatures differ. However, function objects can have different types even when their signatures are the same. In fact, each functional behavior defined by a function object has its own type. This is a significant improvement for generic programming using templates because one can pass functional behavior as a template parameter.
Why can't we just use function pointer instead? Any examples?
Using C style function pointer cannot leverage the advantage of inlining. Function pointer typically requires an additional indirection for lookup.
However, if operator () is overloaded then it's very easy for compiler to inline the code and save an extra call, so increase in performance.
The other advantage of overloaded operator () is that, one can design a function which implicitly considers the function object as argument; no need to pass it as a separate function. Lesser the hand coded program, lesser the bugs and better readability.
This question from Bjarne Stroustrup (C++ inventor) webpage explains that aspect nicely.
C++ Standard (Template) Library uses functional programming with overloaded operator (), if it's needed.
> Does it bring any convenience to use functions as objects in C++?
Yes: The C++ template mechanism allows all other C/C++ programming styles (C style and OOP style, see below).
> Why can't we just use function pointer instead? Any examples?
But we can: A simple C function pointer is an object with a well defined operator(), too.
If we design a library, we do not want to force anyone to use that C pointer style if not desired. It is usually as undesired as forcing everything/everyone to be in/use OOP style; see below.
From C-programmers and functional programmers views, OOP not only tends to be slower but more verbose and in most cases to be the wrong direction of abstraction ("information" is not and should not be an "object"). Because of that, people tend to be confused whenever the word "object" is used in other contexts.
In C++, anything with the desired properties can be seen as an object. In this case, a simple C function pointer is an object, too. This does not imply that OOP paradigms are used when not desired; it is just a proper way to use the template mechanism.
To understand the performance differences, compare the programming(-language) styles/paradigms and their possible optimisations:
C style:
Function pointer with its closure ("this" in OOP, pointer to some structure) as first parameter.
To call the function, the address of the function needs to be accessed first.
That is 1 indirection; no inlining possible.
C++ (and Java) OOP style:
Reference to an object derived from a class with virtual functions.
Reference is 1st pointer.
Pointer to virtual-table is 2nd pointer.
Function pointer in virtual-table is 3rd pointer.
That are 3 indirections; no inlining possible.
C++ template style:
Copy of an object with () function.
No virtual-table since the type of that object is known at compile time.
The address of the function is known at compile time.
That are 0 indirections; inlining possible.
The C++ templates are versatile enough to allow the other two styles above, and in the case of inlining they can even outperform…
compiled functional languages: (excluding JVM and Javascript as target platforms because of missing "proper tail calls")
Function pointer and reference to its closure in machine registers.
It is usually no function "call" but a GOTO like jump.
Functions do not need the stack, no address to jump back, no parameters nor local variables on the stack.
Functions have their garbage collectable closure(s) containing parameters and a pointer to the next function to be called.
For the CPU to predict the jump, the address of the function needs to be loaded to a register as early as possible.
That is 1 indirection with possible jump prediction; everything is nearly as fast as inlined.
The main difference is that function objects are more powerful than plain function pointers as they can hold state. Most algorithms take templates functions rather than plain function pointers, which enable the use of powerful constructs as binders that call functions with different signatures by filling extra arguments with values stored on the functor, or the newer lambdas in C++11. Once the algorithms are designed to take functors it just makes sense to provide a set of predefined generic function objects in the library.
Aside from that there are potential advantages in that in most cases those functors are simple classes for which the compiler has the full definition and can perform inlining of the function calls improving performance. This is the reason why std::sort can be much faster than qsort from the C library.

Converting all functions into classes

I was reading the book Refactoring: Improving the Design of Existing Code by Fowler, where it says to replace function calls with same names classes and call constructors of that class in place of original function call.
My question is is it a good idea to convert all the functions(more or less, except very trivial ones) into objects so that the code becomes more modular?
Thanks,
Expanding a bit on my earlier comment:
In C++ there is absolutely no reason to turn all functions into classes, some kind of processing objects. Functions work well when you just have to compute and return a value.
However, if you have a large function that creates an internal state and uses that in several places during its processing, or (gasp!) stores some state in global variables, that function might be a class in disguise. In that case it can be a good idea to store the state in a class object with several smaller member functions doing their work on that common state.
On the other hand, a function that only computes a value from its parameters is not improved by putting it into a class.
No, why would it? If you have functionality that is logically a function (stateless computation), and there's no compelling reason to implement it as a class, then just implement it as a function.
The advice to "replace function calls with same names classes and call constructors of that class in place of original function call" is plain wrong: how can you replace
int y = f(x);
by a class f and a call to its constructor? A constructor doesn't have a return value! The only way to get this to work is to overload operator() on the class f so you can use one of
int y = f(x)();
int y = f()(x);
both of which are pointless. (Also, you'd have to remember which one of these you need for every function object you define.)
There must be something you're not telling us.
In my opinion, converting functions into classes is absolutely pointless. Why would you want to do that?
When you convert your functions to objects, you're not gaining anything. A method call is in fact the same plain function call, only with a hidden argument, this. In your case, that argument would be redundant because your object is not bearing any state.
The only reason I can think of for converting functions to objects is passing functions as objects to other functions, but for that purpose we have function pointers or boost::function or c++ 0x lambdas.
Definitively no!
It is no point to convert any function to class.
Class is about to manage some state of object and hide information, functions are to global and mostly stateless. A lot of lose classes make software inefficient and unmaintainable.