Problem accessing base member in derived constructor

后端 未结 2 1480
攒了一身酷
攒了一身酷 2020-12-18 08:32

Given the following classes:

class Foo
{
    struct BarBC
    {
    protected:
        BarBC(uint32_t aKey)
            : mKey(aKey)
              mOtherKey(         


        
相关标签:
2条回答
  • 2020-12-18 08:59

    You can't initialize members of a base class through a member initializer list, only direct and virtual base classes and non-static data members of the class itself.
    Pass additional parameters to the base class' constructor instead:

    struct BarBC {
        BarBC(uint32_t aKey, uint32_t otherKey = 0)
          : mKey(aKey), mOtherKey(otherKey)
        {}
        // ...
    };
    
    struct Bar : public BarBC {
        Bar(uint32_t aKey, uint32_t aOtherKey)
          : BarBC(aKey, aOtherKey)
        {}
    };
    
    0 讨论(0)
  • 2020-12-18 09:10

    You can't do this as BarBC constructs the mOtherKey - you can't override it.

    You have either assign new value:

    Bar(...) : ...
    { mOtherKey=aOtherKey; }
    

    Or create additional BarBC constructor that has a parameter of mOtherKey

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