Given the following situation
class Base
{
public:
Base(double par1, double par2)
:
par1_(par1),
par2_(par2)
{}
const double value_;
protected:
const double par1_, par2_;
virtual double Calc_Value() = 0;
};
class Derived_A : public Base
{
public:
Derived_A(double par1, double par2)
:
Base(par1, par2)
{}
protected:
double Calc_Value()
{
// <code to calc value with par1_ and par2_>
}
};
class Derived_B : public Base
{
public:
Derived_B(double par1, double par2, double par3)
:
Base(par1, par2),
par3_(par3)
{}
const double par3_;
protected:
double Calc_Value()
{
// <code to calc value with par1_, par2_ and par3_>
}
};
int main()
{
std::vector<Base*> my_vector;
// do stuff using polymorphism
}
This has been bugging me for some time. I would like to initialize value_
with Calc_Value()
when creating an object of Derived_A
or Derived_B
. I know that only Base
can initialize its const members. Now, my class objects are mostly some sort of containers which calculate the necessary values when they are created. So they should be read only.
I know I could make value_
not const, but that would make it mutable. Most solutions I found in the internet is just to create an additional constructor in Base
but then I would have to declare par3_
in the base class which means, every time there is a derived_A
object it will have a par3_
member variable without ever using it. Also, imagine I want to have more Derived classes with different Calc_Value()
functions, do I then need to declare a constructor for every additional subclass? So far, I have overcome this problem with just making the Calc_Value()
function public and therefore there was no need for a public const member variable. But when accessing the object via a function, the round brackets reduce readability in my opinion, which is why I would like to have a const member variable in Base
.
Is there a common solution to this problem?
const
it must be initialized in the constructor initializer list. – anastaciuvalue_
is only known by the derived class, why is it a member of the base class? You could for example have a pure virtualgetValue
function inBase
and let the derived class supply the value. – supervalue_
of base needs to contain the calculated value, otherwisemyvector[idx]->value_
won't work or what do you mean? Also, do you mean a pure virtual function likeCalc_Value()
but public? I did that but the round brackets reduce readability in my opinion which why I would like to have a const member. I was just wondering if there was a solution which I am not aware of. I am not an experienced coder. – Andi