Re: Declaring a static const member of a class.
Luca Cerone <luca.cerone@gmail.com> wrote in
news:22573415.56.1330778113342.JavaMail.geo-discussion-forums@vbas10:
Hi Ed, thanks a lot for your reply!
On Friday, March 2, 2012 11:49:26 PM UTC, Ed Anson wrote:
You have three problems here:
1. The C++ concept of const does not strictly allow for run-time
initialization such as you desire; and
2. Initialization in the constructor (which might be different for
each instance) is inconsistent with the static definition (which is
shared by all instances).
3. A static const requires a definition with an initial value.
Ok probably I got everything wrong.
I thought that you used const to avoid overwriting a value that has
already been defined; and I thought that static (for class members) is
used to share the same location of memory among all the objects.
In principle you are right. However, 'static const' data members of
classes are normally initialized before main() is entered. This means
that you cannot pass e.g. init file name as the command-line argument as
it will be processed only in main().
If this is not a concern, then you can easily have a static const
std::vector:
#include<iostream>
#include<vector>
class QuadFun{
public:
QuadFun(double a, double b) ; // a and b will be used to initialize
// the private vector y to evaluate the values (x-a)*(x-b)
// x has to be a vector that is shared among all the object of the
class.
private:
static const std::vector<double> x; // this will be a vector of
uniformly
//spaced numbers from 0 to 1. The number of points is
determined
//by reading a configuration file. in this example I set the
//number manually in the main function.
std::vector<double> y;
};
std::vector<double> InitializeVector() {
const int numPoints=50;
std::vector<double> x(numPoints);
for (int i=0; i<numPoints; ++i) {
x[i] = double(i)/numPoints;
}
return x;
}
// static member requires separate definition/initialization
// in a .cpp file:
const std::vector<double> QuadFun::x = InitializeVector();
I'm sorry I'm not aware of the const_cast type... what is it?
If you do not know what is const_cast you need to reread your C++ book.
I actually don't understand something though.
It seems pretty reasonable to me that a class object my depend on
certain parameters input by the user somehow (keyboard, reading a file
etc. etc.).
Isn't there a way to "parameterize" a class, so that its members will
depend on certain parameters?
It becomes difficult with a 'const static' data member as the
initialization may happen too early. A 'const static' local variable
inside a function would be more flexible in this regard.
Thanks again for your answer.
I'm sorry if I ask silly question, I'm a 3weeks "experienced" c++
programmer, and after 10 years of Matlab programming I feel like I've
never programmed before :)
You are welcome. Just do not expect to be proficient in C++ in another 3
weeks, it will take years.
hth
Paavo