Reputation: 85
Let's say this is in Foo.h:
class Foo {
private:
const int MAXIMUM;
}
How do I initialize MAXIMUM to a certain value (100 in this case) in the Foo.cpp file? I tried
Foo::Foo() {
MAXIMUM = 100;
}
and got the error "expression must be a modifiable lvalue". Then I tried
const int Foo::MAXIMUM = 100;
and got the error "a nonstatic data member may not be defined outside its class". And that basically answers my question as "it's just not possible" but that just means my university messed up on the header file. So, is this possible or not?
Note: This is a university assignment, so I can't change the header file. I assume the logical solution would be to set MAXIMUM to 100 in the header file.
Upvotes: 0
Views: 1457
Reputation: 670
"Const" and "Reference" variables are need to be initialized before class object is created. In your case,
Foo::Foo() { // **End of this line, object is getting created.**
MAXIMUM = 100; // *This line, gets Error: "expression must be a modifiable lvalue"*
}
to avoid this, you must use "Initialization list" where the value is assigned to variable before class constructor creates object.
Fix:
Foo::Foo():MAXIMUM(100) { // const variable is initialized
MAXIMUM = 200;
}
Upvotes: 0
Reputation: 3580
You can initialise const variables in two ways
In line initialisation
class Foo {
private:
const int MAXIMUM = 100;
};
Using initialisation list
class Foo {
Foo()
: MAXIMUM(100) {
}
Foo(const int MAXIMUM)
: MAXIMUM(MAXIMUM) {
}
private:
const int MAXIMUM;
}
In the below statenter code here
ement
Foo::Foo() {
MAXIMUM = 100;
}
MAXIMUM
is already created and you are trying to modify its value, which is not allowed for const
variables.
In the below statement
const int Foo::MAXIMUM = 100;
MAXIMUM
is not a static variable, so it will be bind with an object. You cannot access MAXIMUM
using class name.
Upvotes: 3