Reputation: 321
As the title suggests, I've always thought of constants values to be set and cannot be modified however I've noticed you are able to change it in the constructor. As you can see I created a string name which is later to be set as whatever I pass through the constructor, why is this allow?
Example code:
#include <iostream>
using namespace std;
class test{
const string name;
public:
test(const string &nam) : name(nam) {}
string get_name() { return name; }
};
int main ()
{
test a("Tom");
cout << a.get_name();
// const string t1;
// string t2 = "changing"; this causes an error
// t1 = &t2;
return 0;
}
Upvotes: 0
Views: 90
Reputation: 38218
You aren't changing the const string
. You're initializing it.
const
means that once the variable has been initialized, it cannot be changed. It does not mean constexpr
(which means a compile-time constant expression).
const
values can be set at run time. For example:
#include <iostream>
int main() {
int x;
std::cin >> x;
const int y = x; // This is totally fine.
std::cout << "You entered the number " << y;
}
In the above example, the value of y
is determined at runtime (after reading the value x
). It is initialized with the value of x
, and after it has been initialized, we can't change its value.*
It's the exact same with a const
member.
Changing a variable implies that it exists, has a value, and then you set it to a new value. That's not the case here. The variable/member does not exist until the constructor is called. Since it does not exist, it cannot possibly have some previous value. Instead, you're creating the variable/member and giving it its (first and only) value, all at the same time (which is what we mean when we talk about initialization). There is no change in that process.
*const_cast
lets us change the value of a const
reference to a variable that isn't originally const
. So workarounds exist. But if the original variable (not just the reference) is const
you'll invoke undefined behavior if you modify it. Thankfully you have to go out of your way to do this, so if you do it's probably not an accident.
Upvotes: 7