Executable Code in C++ Class - c++

I need to execute code in a class definition in C++. I have a macro to add a method to a function pointer after the definition of the method. It expands to a call to std::map.insert that it needs to execute in the definition (think of how Ruby executes code in class definitions).
The class definition might look something like this after macro expansion:
bindings.insert(pair<char, ReturnType (*)(FirstArgument, SecondArgument)>("theFunction",&theFunction));
Would this execute in the definition?

You need to use a global, its constructor will then execute during program initialization.
See for example these questions and these for how to make sure that map.insert doesn't execute until after the map is constructed.

No, you can't have executable code outside function body in class declaration. (if I understand you correctly).
At which point do you expect it to be executed?

You can put this in the constructor.

Related

Is there an analogous function like Do() for ExpectCallFunc or OnCallFunc?

For mocking member methods with ExpectCall or OnCall you can use the Do method.
But for static functions if you try Do the compiler will tell you that Do is not a member of the Call class.
Is there a similar mechanism?
Ok my bad.
Apparently putting the Do behind the Return does not work:
mocker.OnCallFunc(ReadFile).Return(true).Do(ReadFileMock);
but this just compiles with no problem at all: mocker.OnCallFunc(ReadFile).Do(ReadFileMock).Return(true);
I didn't know there was an obligatory order.
And I should have supplied code samples.

Private C++ member function vs C function

I have a C++ class, and in one of the member functions there is a duplicate section of code. So I've extracted this out into a function, however only this member function will call this new function. At the moment it's just a c function defined in the cpp file and not declared anyway else.
Is there any advantage to making this a private C++ member function, the code in the function itself doesn't use any instead variables of the class.
Well, if it's any addition to the argument, the newest CppCoreGuidelines say that you should "C.5: Place helper functions in the same namespace as the class they support". So they shouldn't be a part of the actual class, but part of the namespace that they reside in.
If you add it to the class then it becomes part of the classes signature.
As such making changes to the function signature would change the class signature. Given it would be a private function it is not likely that you would gain much by exposing it in that way.
If though it needs to access internals of the class then having as part of the class would likely simplify its implementation.
If it does not need to access the internals you can make add it to an anonymous namespace within the cpp file. That way the function symbol will not be exposed anywhere that is is not needed.
(Sort of an extended comment)
You've declared a free function in the .cpp file.
This a good design decision as other answers point out. The clearest thing you can have is a method only visible from that .cpp file that can't see or change state. I might be tempted to put it in the same namespace as the class as per the CppCoreGuidelines.
Equivilently, you could have declared a private static member function in your header file. This is static in the C#/Java sense rather than in either of the C senses (C++ has all of these meanings). However, I don't see the benifit as the only thing you gain is unnecessary recompilations.
Yes. Putting the function in class defines scope and context of it. This makes maintenance easier and also will allow you to extend its functionality in the future without significant code rewriting. Actually, in such cases I usually prefer making the function static in the class, i.e., meeting somewhere in the middle.

How to know if function in c++ are unused if they are in a class?

Is there a method to know if a private function isn't used within the definition class?
Also, I need to know if there some public function of the class which is not used outside the class. How can achieve this?
The solution depends heavily on the situation.
In many cases, you can simply grep or ag the source for calls to the function. Also, there are tools like cppcheck that can analyze a source base and tell you this.
However, if you don't have source then there are other methods.
Add code to the functions that will output somehow visibly (perhaps to a logfile) when called. This is what gcc's Code Coverage functions do.
Remove the function and see whether your project still compiles and links.
You should remove the definition (in the cpp file) only, and leave the declaration in the header. Otherwise overload resolution could mask the places where your function is called.

GDB break on object function call

I'm debugging an issue, and I want to break on every method call that has a specific object as the 'this' parameter. Is this possible in GDB?
It's easy. You can use command like b A::a if (this==0x28ff1e).
The this parameter should only be the methods that are included in the class itself. So you should just need to set breakpoints for all Of the methods of the class you are looking at. I'm not sure there is a simple way to do that though.
I want to break on every method call that has a specific object as the 'this' parameter
This means that you want to break on every member function of a particular class for which the object has been instantiated.
Let's say for convenience that all the member functions are defined in a particular cpp file such as myclass_implementation.cpp
You can use gdb to apply breakpoint on every function inside myclass_implementation.cpp this way:
rbreak myclass_implementation.cpp:.
Let's say you want to break on some specific functions such as getter functions which start with Get, then you can use gdb to apply breakpoints this way:
rbreak myclass_implementation.cpp:Get*

Run Code Before Every Function Call for a Class in C++

I would like to run some code (perhaps a function) right before every function call for a class and all functions of the classes that inherit from that class. I'd like to do this without actually editing every function, Is such a thing even possible?
I would settle for having a function called as the first instruction of every function call instead of it being called right before.
AspectC++ is what you want. I haven't used it myself, but Aspect-Oriented Programming paradigm tries to solve this exact problem.
I would suggest using the Non Virtual Interface idiom. All public functions are non-virtual. All virtual functions are protected or private. Public members delegate the calls to virtual members and are usually implemented as inline functions.
This is the way IOStreams are implemented in STL. You can read more about it at C++ Wikibooks.
Intent: To modularize/refactor common before and after code fragments (e.g., invariant checking, acquiring/releasing locks) for an entire class hierarchy at one location.
Regards,
Ovanes
The following might be a bit of an overkill - but how about?
http://msdn.microsoft.com/en-us/library/c63a9b7h.aspx
Another thing you could consider is using something like the [boost/C++0X] shared_ptr wrapper, where you call your custom function on the '->' overload before returning the class instance pointer. It involves modifying usage but not the underlying class, and I've used it a couple times to achieve the same effect. Just another thought.
The somewhat inconvenient way where to build a wrapper class that takes an object of your base type and calls the surrounding function and then the function that you wanted to call. This would be something like a decorator.
The best you can do is to declare a set of virtual functions as protected and have the developers inheriting from the class override the virtual functions. The interface used by the base class can be public, which executes the desired code before passing information to the protected virtual method.
For example:
class Base {
public:
void MyMethod(void) { /* Insert code here */ YourMethod(); }
protected:
virtual void YourMethod(void) {}
};
If the developer knows that he has a specific subclass, he can still bypass your code simply by using a dynamic_cast, and using his own method set. As such, you may want to follow the other suggestions already posted that do not involve the base C++ language.
This sounds like what a profiler does. Have you looked at the source for any profiling tools?
You could also do this with the Curiously recurring template pattern (CRTP).
Using g++, you could use the option -pg for the respective compilation units, which makes the compiler generate a call to the function mcount at the start of every function. mcount is usually provided by profiling tools like gprof, but you can also implement it yourself. You should however make sure that
mcount has C linkage (and is not C++-style name-mangled), i.e. by implementing it as a C function and compiling with a pure C compiler like gcc.
the compilation unit containing mcount is not compiled with -pg.