Assign a value to a variable in private section of class in C++

137 views Asked by At

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?

2

There are 2 answers

2
Paul Sanders On BEST ANSWER

Just in case the comments don't make it clear (I found them a bit fragmented):

std::string foo = "randomValue";

is (as you yourself say) initialisation. It initialises foo when 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:

std::string foo;
foo = "randomValue";

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).

3
Phoned_Leek25 On

The short answer is that foo = "randomValue"; is not a declaration it's an initialization. The reason this is significant (and this is heavily summarizing) when you create a class, anything that's not inside a function is intended to be a declaration (allocating memory, etc.) and everything inside a function is more "processing" instructions such as initializations. Typically the best thing to do is to declare and then initialize in instructor such as:

class MyClass
{
private:
    std::string foo; //valid decleration in MyClass's scope
public:
    MyClass()
    {
        foo = "randomValue"; //constructor assigns value
    }
};

The reason this happens is also similar to how you can't assign things later outside of a function's scope (i.e. global). For example you can't run this:

#include <iostream>
std::string foo; //valid declaration in global scope
foo = "hi"; //invalid initialization, can't be global.

int main()
{
    std::cout << foo;
}

but you can run this:

#include <iostream>
std::string foo; //valid global declaration

int main()
{
    foo = "hi"; //valid initialization
    std::cout << foo;
}

If at all helps, the difference between declaration and initialization, is that declaration creates the container (memory address/location) an the initialization sets that actual contents of that container. For reference, this is why if you just declare a variable and print it, you get (typically) gibberish, as it's what's at that memory address at the moment since it has not yet been replaced with whatever you want to initialize it as.