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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With