P
pembed2003
Hi,
I have the following:
class person{
public:
person(){name = new char[6]; strcpy(name,"peter");}
~person(){delete[] name;}
const char* getName(){return name;}
private:
char* name;
};
int main(int argc,char** argv){
person p;
char* s = (char*)p.getName();
s[0] = 'f';
std::cout<<p.getName()<<std::endl;
}
The above prints:
feter
What I want to do is allow my getName() function to return the name of
person but don't allow the caller to modify the name. Any idea?
I can do:
char* person::getName(){
char* s = new char[strlen(name) + 1];
strpcy(s,name);
return s;
}
But this approach has 2 drawback:
1. Everytime the getName() function is called, a copy of name has to
be made which is slow
2. The caller has to remember to free s
Is ther any other solution?
Thanks!
I have the following:
class person{
public:
person(){name = new char[6]; strcpy(name,"peter");}
~person(){delete[] name;}
const char* getName(){return name;}
private:
char* name;
};
int main(int argc,char** argv){
person p;
char* s = (char*)p.getName();
s[0] = 'f';
std::cout<<p.getName()<<std::endl;
}
The above prints:
feter
What I want to do is allow my getName() function to return the name of
person but don't allow the caller to modify the name. Any idea?
I can do:
char* person::getName(){
char* s = new char[strlen(name) + 1];
strpcy(s,name);
return s;
}
But this approach has 2 drawback:
1. Everytime the getName() function is called, a copy of name has to
be made which is slow
2. The caller has to remember to free s
Is ther any other solution?
Thanks!