Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initialisation of const member of base class into derive class

public:
    const int x;
    base():x(5){}

};

class der : public base {
public:
    der():x(10){}
};

der d;

My aim is when instance of base class is created it will initialise x as 5 and when instance of der class is created it will initialise x as 10. But compiler is giving error. As x is inherited from class base, why is it giving error?

like image 410
user966379 Avatar asked Dec 28 '25 06:12

user966379


1 Answers

You can make this work with a little adjustment...

#include <cassert>

class base
{
public:
    const int x;
    base()
        :x(5)
    {
    }

protected:
    base(const int default_x)
        :x(default_x)
    {
    }
};

class der: public base
{
public:
    der()
        :base(10)
    {
    }
};

struct der2: public base
{
    der2()
        :base()
    {
    }
};

int main()
{
    base b;
    assert(b.x == 5);
    der d;
    assert(d.x == 10);
    der2 d2;
    assert(d2.x == 5);
    return d.x;
}

This provides a constructor, accessible by derived classes, that can provide a default value with which to initialise base.x.

like image 95
Johnsyweb Avatar answered Dec 30 '25 23:12

Johnsyweb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!