In C++, constructors must initialize const
variables using initialization lists.
What i开发者_开发知识库f my constructor needs to compute the values of those fields? Say via a database lookup or simple computation.
The factory pattern could be applied here, but it seems a bit heavy. I'm considering static methods like X::GetX(param1, param2)
that will compute the values and call a private constructor.
Is there a better or more popular pattern that could be used here?
No need for calling a private constructor, you can call static methods (or in some cases, even non-static ones) directly from the initializer list. For example:
class testclass {
public:
testclass::testclass(int n): memberdata(fn(n)) { }
private:
int fn(int n) {
// Various calculations on 'n'
return 12;
}
int memberdata;
};
You can call static functions within the initialisers, and those functions can contain whatever logic you please.
You can call the method inside the initializer list itself:
class A {
public:
A () : t_Const(X::Get(param1, param2)) { } // constructor can be public
const int t_Const; // this is your variable
};
Why you need a private constructor!
精彩评论