Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return char* from class?

Tags:

c++

class

I want to return a name, and while the main should be able to alter it (in main's scope), it should not change in the class.

If I do it like this:

char* get_name(){
    char* name = new char[sizeof(_name)+1];
    strcpy(_name,name);
    return name;
}

do I have to delete[] at some point? And when?

Edit: I don't believe it's the same problem as pointer to local variable since the problem here is how to delete it after i use it.

like image 333
user1824034 Avatar asked Oct 16 '25 03:10

user1824034


2 Answers

Well, that's the problem with manual memory management. Indeed, if you want to return a copy, then it would be the caller's responsibility to free the memory, which is extremely error prone. That's why C++ has std::string class which handles the memory;

std::string get_name() const //note the const on member function
{
    return _name; //this will work even if _name is char*, btw
}
like image 89
Armen Tsirunyan Avatar answered Oct 18 '25 19:10

Armen Tsirunyan


As others have said, using std::string is probably a better option. If you want to use a char* instead, I would suggest simply returning a const char*:

const char* get_name() {
    return _name;
}

You will be returning a const reference, meaning that the calling code should not change it. The way you are doing it, you will indeed have to delete after every call to get_name(), which is not ideal.

like image 22
Signal Eleven Avatar answered Oct 18 '25 20:10

Signal Eleven