Lets say I have the member:
char* name;
When writing a getter function to this member, is this the correct way:
char* getName(){
return name;
}
But when we do this, now user of this class can change name without a setter since the user has the pointer to the heap variable.
I thought of this solution:
char* getName(){
char* otherName;
otherName = new char[10];
strcpy(otherName, name);
return otherName;
}
But now, since the function creates a heap variable, the user can forget to delete the heap variable and it will be garbage. That's why this implementation does not feel the correct way to implement the getter function for this member too.
How should I implement it?
As mentioned in the comments, you really should use std::string
; anything else is just bad (very bad) C++. But if you're constrained to using char*
, what's wrong with
char const* getName() const { return name; }
Just return a pointer which doesn't allow modification.
Note that this still can be a source of lifetime issues -- anything which calls the destructor of the object, or causes the object to delete the pointed to memory, will invalidate the returned pointer. This is perhaps an even stronger argument for using std::string
.
Whatever you do, do not return a newly allocated copy of the string, expecting the client to delete it. The client won't, and you'll leak memory.