Search code examples
c++loggingmethodsfunction-calls

Making all class methods call the same function


So, I've got this situation:

#include "ActionLog.h"
class Library{
        ActionLog aLog;
        // ... the rest of it is private, mind you :D
    public:
        Library(...);
        void addBook(...);
        void removeBook(...);
        // ... aaand there's a whole bunch of these :)
    };

Now, class ActionLog has a public method void log(...);. It should, once implemented, record the beginning of any activity listed as a method of class Library (and eventually it's success/failure, which is optional).

I'm wondering this: Is there some more elegant way of making every class Library's method call the aLog.log(...); method when/before it starts executing? By "elegant" I mean other than just calling it explicitly in every single method...

I am aware of the Python version of the solution for the similar problem, but I'm not familiar with Python, so I'm not even sure that the same class-related principles apply.


Solution

  • C++ doesn't have any means of reflection built-in. There's no way to list methods neither in runtime, nor in compile-time. The best you can do is to hide logging into some #define that you will use to define every method, but preprocessor usage is an antipattern in modern C++.

    Stick to the current approach.