I know how to initialize const member in the initializer list, but that requires to know the value to be assigned already when calling the constructor. From what I understand, in java it's possible to initialize a final member in the constructor body, but I haven't seen an equivalent in c++ ( Java's final vs. C++'s const )
But what to do when the initialization is relatively complex? The best I could come up, is to have an initialization function that returns directly an instance. Is there something more concise?
Here is an example (https://ideone.com/TXxIHo)
class Multiplier
{
const int mFactor1;
const int mFactor2;
static void initializationLogic (int & a, int & b, const int c )
{
a = c * 5;
b = a * 2;
}
public:
Multiplier (const int & value1, const int & value2)
: mFactor1(value1), mFactor2(value2)
{};
/*
//this constructor doesn't initialize the const members
Multiplier (const int & value)
{
initializationLogic(mFactor1,mFactor2, value);
};
*/
//this initializes the const members, but it's not a constructor
static Multiplier getMultiplierInstance (const int & value)
{
int f1, f2;
initializationLogic(f1,f2, value);
Multiplier obj(f1,f2);
return obj;
}
Aucun commentaire:
Enregistrer un commentaire