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

后端 未结 9 1267
被撕碎了的回忆
被撕碎了的回忆 2021-02-15 13:08

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 t

9条回答
  •  清歌不尽
    2021-02-15 13:36

    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.

提交回复
热议问题