Ref data member showing no change

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <string>

class Person {
		std::string name;
		Person* bestFriend; 
	public:
		Person (const std::string& personName) {name = personName;}
		void BestFriend (Person* person) {bestFriend = person;}
		const Person* BestFriend () const {return bestFriend;}
		const std::string& bestFriendsName () const {return bestFriend->name;}  // returning std::string&, not std::string
		std::string Name () const {return name;}
};

int main () {
	Person *sandy = new Person ("Sandy"), *mary = new Person ("Mary");
	sandy->BestFriend (mary);
	std::string sandysBestFriendsName = sandy->bestFriendsName();
	std::cout << "sandysBestFriendsName = " << sandysBestFriendsName << std::endl;  // Mary
	sandysBestFriendsName = "Marie";
	std::cout << "sandysBestFriendsName = " << sandysBestFriendsName << std::endl;  // Marie. As expected.
	std::cout << "Mary's new name is " << mary->Name() << "." << std::endl;   // Mary.  Why???
	
	Person& maryRef = *mary;
	Person maryWithNewName ("Maria");
	maryRef = maryWithNewName;
	std::cout << "Mary's new name is " << mary->Name() << "." << std::endl;  // Maria. As expected.
	
	std::cin.get();
	return 0;
}


Can someone explain to me why Mary's name did not change in the third output? The fourth output also uses reference and did change her name successfully, so why didn't it happen in the third output? Removing the const qualifiers in Person::bestFriendsName() still results in the same thing.
Last edited on
You are missing an ampersand on line 18 - simple mistake ;)

Also, references cannot be reassigned - on line 26 you are invoking the copy assignment operator. I can't tell whether you knew that already or not, I am saying it just in case.
Last edited on
Topic archived. No new replies allowed.