Reputation: 58883
In an inherited class constructor, I want to use a class constant member that hides the base class one from the base class constructor:
#include <string>
#include <iostream>
class BaseClass {
private:
const int constant_variable { 21 };
public:
int mutable_variable;
BaseClass(): mutable_variable(constant_variable) {};
};
class DerivedClass: public BaseClass {
private:
const int constant_variable { 42 };
public:
using BaseClass::BaseClass;
};
int main () {
DerivedClass dc;
std::cout << dc.mutable_variable << std::endl; // 21, but I want it to be 42
return 0;
}
In the example code, for instance, BaseClass' constructor uses its own value of constant_variable
while I'd like it to use the DerivedClass' constant_variable
.
How to do this in c++?
Upvotes: 1
Views: 463
Reputation: 6117
Just override the non mutable variable in the derived class constructor
#include <string>
#include <iostream>
class BaseClass {
private:
const int constant_variable { 21 };
public:
int mutable_variable;
BaseClass(): mutable_variable(constant_variable) {};
};
class DerivedClass: public BaseClass {
private:
public:
DerivedClass()
{
mutable_variable = 42;
}
};
int main () {
DerivedClass dc;
std::cout << dc.mutable_variable << std::endl; // returns 42
return 0;
}
Upvotes: 0
Reputation: 170074
I don't know if you need the constant member in the base, but if you want to specify its value from a derived class constructor, as well as that of the mutable member, you can just use a protected c'tor:
class BaseClass {
private:
const int constant_variable { 21 };
protected:
BaseClass(int init) : constant_variable{init}, mutable_variable{init}
{}
public:
int mutable_variable;
BaseClass(): mutable_variable(constant_variable) {}
};
class DerivedClass: public BaseClass {
public:
DerivedClass() : BaseClass(42) {}
};
You should know that constant_variable
is not a compile time constant, it occupies space in each and every object.
Upvotes: 4
Reputation: 10756
Make the base class constructor take the value as a defaulted parameter.
BaseClass::BaseClass(int constant = 21)
: mutable_variable(constant)
{}
Then the derived class can provide something different
DerivedClass::DerivedClass()
: BaseClass(41)
{}
Upvotes: 1
Reputation: 15162
The base class constructor will have to be told about the value, it has no idea the derivation even occurs. The easiest would be to alter your base class ctor to take a parameter with the value of interest.
Upvotes: 0