Printing derived class name in base class

前端 未结 3 542
我寻月下人不归
我寻月下人不归 2021-01-12 05:52

How can I print out the derived class name from the base class without chaining constructors all the way down. In other words is it possible to do this strictly from the bas

3条回答
  •  甜味超标
    2021-01-12 06:20

    you can provide an initialization function that needs to be called from each constructor.

    class Base {
    protected:
      Base() { init(typeid(this).name()); }
      void init(std::string id) {
        std::cout<<"Creating "<

    You somehow need to make sure, that subsequent inits will safely supersede the changes of previous ones:

    Creating P4Base
    Creating P5Child
    Creating P10GrandChild
    Creating P15GrandGrandChild
    Creating P4Base
    Creating P5Child
    Creating P10GrandChild
    Creating P4Base
    Creating P5Child
    

    I intend to use it purely for debugging purposes, which is why something to throw into the base class would be convenient.

    have you considered adding a macro to your code to print the debug output?

    #ifdef DEBUG
      #define PRINT_CLASSNAME std::cout<<"Creating "<

    You need to add it to your constructors once, but if you want to disable it (temporarily) you just undefine it?

提交回复
热议问题