Search code examples
c++inheritancepolymorphism

Redefine a constant member variable in inherited class


Say I wish to define a member variable in a parent class and set its value in an inherited class. Perhaps these identify functionality available in the class or the nature of the child class. For example:

class A
{
public:
    inline int getX() { return x; }
protected:
    const int x = 0;
};

class B : public A
{
protected:
    const int x = 10;
};

class C : public A
{
protected:
    const int x = 50;
};

It should go without saying that scope issues will prevent the above from working properly. However, is there a way to make this work as intended?

Since the variable is meant to identify the nature of the inherited classes, I would prefer if it were const - this problem would not arise if it were not const and merely redefined in the constructor, so far as I can tell.


Solution

  • While fiddling with the compiler trying to make sure my example code made sense, I actually came across the fact that the way I was attempting to define the constants was C++11-specific. That led me to look into the ways it was done before, and I found this question, which shed some light on the matter indirectly.

    Defining a variable in this way should be done by having the base class take an argument in its constructor, in the form of:

    class A
    {
    public:
        A( int type ) : x(type) {}
        inline int getX() const { return x; }
    protected:
        const int x;
    };
    
    class B : public A
    {
    public:
        B() : A(10) {}
    };
    
    class C : public A
    {
    public:
        C() : A(50) {}
    };
    

    This will work as intended and allow the constant x to be redefined by inherited classes.