Is it a good idea to replace getters and setters with a single function returning a reference? For example, instead of this,
class Person {
std::string name;
public:
std::string GetName() { return this->name; }
void SetName(std::string& toSet) { this->name = toSet; }
};
Is this a good idea,
class Person {
std::string name;
public:
std::string& Name() { return this->name; }
};
...
...
Person p;
p.Name() = "Joe"; // Write.
std::string local = p.Name(); // Read.
Does the second code have some problem?
But in C#, methods return object by reference. For example,
class Person
{
string name;
public Person(string _name) { this.name = _name; }
public string GetName()
{
return this.name;
}
public void SetName(string _name)
{
this.name = _name;
}
};
class Company
{
Person manager;
public Company()
{
this.manager = new Person("Mr. K");
}
// The Person object is returned by reference.
// This is equivalent to "Person& GetManager()" in C++.
public Person GetManager()
{
return this.manager;
}
};
...
...
Company comp = new Company();
// Equivalent to,
// Person& p = comp.GetManager();
Person p = comp.GetManager(); // p is a reference to comp.manager
p.SetName("Mr. L"); // This statement changes comp.manager.name
Console.WriteLine(comp.GetManager().GetName()); // Prints "Mr. L"
In the above code, comp.manager.name
wouldn't have changed if the method GetManager()
returned Person
by value. So, this code isn't dependent on return value optimization.
Isn't this code a violation of encapsulation?