What (not) to do in a constructor

后端 未结 13 1659
悲&欢浪女
悲&欢浪女 2020-12-12 17:33

I want to ask you for your best practices regarding constructors in C++. I am not quite sure what I should do in a constructor and what not.

Should I only use it for

相关标签:
13条回答
  • 2020-12-12 18:05

    The most common mistake to do in a constructor as well as in a destructor, is to use polymorphism. Polymorphism often does not work in constructors !

    e.g.:

    class A
    {
    public:
        A(){ doA();} 
        virtual void doA(){};
    }
    
    class B : public A
    {
    public:
        virtual void doA(){ doB();};
        void doB(){};   
    }
    
    
    void testB()
    {
        B b; // this WON'T call doB();
    }
    

    this is because the object B is not yet constructed while performing the constructor of the mother class A... thus impossible for it to call the overriden version of void doA();


    An example where polymorphism will work in constructor:

    class A
    {
    public: 
        void callAPolymorphicBehaviour()
        {
            doOverridenBehaviour(); 
        }
    
        virtual void doOverridenBehaviour()
        {
            doA();
        }
    
        void doA(){}
    };
    
    class B : public A
    {
    public:
        B()
        {
            callAPolymorphicBehaviour();
        }
    
        virtual void doOverridenBehaviour()
        {
            doB()
        }
    
        void doB(){}
    };
    
    void testB()
    {
       B b; // this WILL call doB();
    }
    

    This time, the reason behind is: at the time the virtual function doOverridenBehaviour() is invoked, the object b is already initialized (but not yet constructed), this means that its virtual table is initialized, and thus can perform polymorphism.

    0 讨论(0)
提交回复
热议问题