Posts

Showing posts with the label functions

C++: Link errors caused by inline functions

Spanish version / Versión en Español When we want a C++ function to be inlined, that is, to have its calls replaced by its code in order to save the calling overhead, one way to achieve is to declare and define it in the .h file, and add the inline keyword. However, that's just a hint to the compiler, he'll decide whether to inline it or not. However, if we are keen on separating declaration and definition, we should declare the function in the .h file, without the inline keyword, and define it in the .cpp with the inline keyword. So far, so good. But there's a catch: If we go for the "cpp inline" approach, and the function is called from another compilation unit (.cpp), we'll get a linking error saying something like the function definition cannot be found. In this case, we have two choices: Place the function definition in the .h file, but outside of the class declaration. This avoids cluttering its interface. This way

C++: Pointers to member functions

Spanish version / Versión en Español This is quite an advanced C++ topic. In both plain C and C++ there are pointers to functions, which allow us to dynamically select the function to invoke from many which have the same signature. A typical example of this is defining a few comparison functions, all with the same signature, in order to dynamically select how to sort a collection (ascending, descending, alphabetically, etc). C++ brings in a new concept over C: pointers to member functions. Most of the times, plain pointers to function are not very Object Oriented, since they are static and all. The C++ syntax for declaring pointers to member functions is similar to that of pointers to functions, we just have to specify the class: // Generic syntax // functionReturnType (ClassName::*nameOfPointerToMemberFunctionVariable)( functionArguments ); // Concrete example LRESULT (CCoConsola3D::*onMouseWheelHandler) ( UINT, WPARAM, LPARAM, BOOL& ); The concrete example declare