views:

74

answers:

2

Given the following classes:

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

    public:
        const uint32_t mKey;
        const uint32_t mOtherKey;
    };


    struct Bar : public BarBC
    {
        Bar(uint32_t aKey, uint32_t aOtherKey)
            : BarBC(aKey),
              mOtherKey(aOtherKey) // Compile error here
    };
};

I am getting a compilation error at the point indicated:

error: class `Foo::Bar' does not have any field named `mOtherKey'.

Can anyone explain this? I suspect it's a syntactical problem due to my Bar class being defined within the Foo class, but can't seem to find a way around it.

This is simple public inheritance, so mOtherKey should be accessible from the Bar constructor. Right?

Or is it something to do with the fact that mOtherKey is const and I have already initialised it to 0 in the BarBC constructor?

+5  A: 

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)
    {}
};
Georg Fritzsche
@George - thanks. I was trying to default initialise all of the const data members in the base class constructor (to avoid a compilation error), and then set derived class specific members in the derived constructors (while still leaving the members in the base class). Not the best class structure by any measure. But I didn't realise the initialiser list had restrictions like this.
LeopardSkinPillBoxHat
+1  A: 

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

Artyom