Hi, I have a question, let me explain...
Instance one: string object created in main, another temporary copy is created in a different section of memory, then the area of memory allocated to m_Name is filled with the string value passed to it by the member initialiser.
1 2 3 4 5 6 7 8 9 10 11 12 13
|
class Player
{
public:
Player(string name);
private:
string m_Name;
};
Player::Player(string name) :
m_Name(name) {}
int main() {
string name = "sam";
Player sam(name);
|
Instance two: adding "&" to the string member initialiser for Player, makes it accept a reference to string name in main(), and passes the original value of name in main() over rather than creating an additional copy first.
1 2 3 4 5 6 7 8 9 10 11 12 13
|
class Player
{
public:
Player(string& name);
private:
string m_Name;
};
Player::Player(string& name) :
m_Name(name) {}
int main() {
string name = "sam";
Player sam(name);
|
Instance three(/four): However, if I try and pass a string literal to the the object on initialisation in main(), i.e.
... it won't work - is this because it wishes to create a reference to a memory address that doesn't exist yet? I don't entirely understand, because if I change the class constructor to:
1 2
|
Player::Player(const string& name) :
m_Name(name) {}
|
... I can now pass string literals directly. I don't understand why, if someone could succinctly explain this to me I'd be so grateful. I'm sure it's quite simple but I've been banging my head against a wall trying to understand this concept, thanks!