How can you assign a variable in the private section of a class in C++?
I tried to do it the following way:
private:
std::string foo;
foo = "randomValue";
But that results in an error message.
Though if I declare and assign a value to the variable at once, like this:
private:
std::string foo = "randomValue";
it works.
Why does the second way work but the first one not?
Just in case the comments don't make it clear (I found them a bit fragmented):
is (as you yourself say) initialisation. It initialises
foowhen the object is constructed. It works from C++11 on and is, IMO, the right way to do it (because you can initialise all your member variables in the same place, so if you subsequently add one, you're not going to forget).Whereas:
if it were legal, would be assignment - i.e. it assigns a value to a variable that already exists. But you can only do that in the body of a function (including the constructor).