Reputation: 896
This is a question to understand the correct way to implement a get function in the below scenario.
I got the below class:
class A
{
string m_sName;
public:
A(): m_sName ("this") {}
const string& getName() const
{
return m_sName;
}
};
The problem with the above implementation of the get function is, it allows the client to modify the data member. That's:
int main ()
{
A a;
const string& data_mem = a.getName();
string& s = const_cast<string&> (data_mem);
s += " Pointer";
cout << a.getName().c_str () << endl;
return 0;
}
The output would be: this Pointer
I know we can use reference parameter for get function or simply return string. But both will create new object.
Is there a better way to do this? Or prohibit const_cast (on a user defined class)?
Upvotes: 0
Views: 102
Reputation: 620
Add another version of getName() that isn't marked as a const method and returns a non-const string&:
string& getName() { return m_sName; }
That will return a reference to the string in the instance of A, and won't create a copy. It will however amend the string in the class.
I should point out this is the wrong way to do things in OO terms, both in terms of encapsulation and data hiding. Your class's abstraction for how the name is stored is leaking to the outside world. The correct approach would be to add an UpdateName or AppendToName method.
Upvotes: 0
Reputation: 31447
You could avoid the problem completely by simply returning by value
string getName() const
Upvotes: 4
Reputation: 234635
C++ gives you the ability to shoot yourself in the foot.
Programmers should use const_cast
with extreme caution: being aware that the behaviour on using it to cast away the const
on an object that was initially declared as const
is undefined.
Code analysis tools could help you.
Upvotes: 7