Virtual base class data members

前端 未结 5 2126
我在风中等你
我在风中等你 2021-01-05 04:30

Why it is recommended not to have data members in virtual base class?

What about function members? If I have a task common to all derived classes is it OK for virtua

5条回答
  •  暖寄归人
    2021-01-05 05:09

    The core advice is to have a default-constructor in the virtual base. If you don't, then every most-derived class (ie. any subclass) must call the virtual base ctor explicitly, and that leads to angry colleagues knocking on your office door...

    class VirtualBase {
    public:
        explicit VirtualBase( int i ) : m_i( i ) {}
        virtual ~VirtualBase() {}
    
    private:
        int m_i;
    };
    
    class Derived : public virtual VirtualBase {
    public:
        Derived() : VirtualBase( 0 ) {} // ok, this is to be expected
    };
    
    class DerivedDerived : public Derived { // no VirtualBase visible
    public:
        DerivedDerived() : Derived() {} // ok? no: error: need to explicitly
                                        // call VirtualBase::VirtualBase!!
        DerivedDerived() : VirtualBase( 0 ), Derived() {} // ok
    };
    

提交回复
热议问题