Reputation: 5235
I have a very simple class with some char* members. Is strcat
the best way to set their values?
class CImage {
public:
CImage() {};
char* Name;
};
void AddImage(const char* Name)
{
CImage* img = new CImage();
strcpy(img->Name, Name); // Is this correct or the best way?
}
Upvotes: 0
Views: 1015
Reputation: 4369
You must first allocate dynamically enough memory to store the string like this
img->Name = new char[strlen(Name) + 1];
strcpy(img->Name, Name);
And if you do so, you should then deallocate memory using delete[]
Also, you should consider incapsulating your string and its initialization in constructor.
The best way to store strings, however, is std::string
Upvotes: 4
Reputation: 206536
Strongly advice you to drop the char *
and use std::string
.
With char *
as member you need to bother about allocating(in constructor) and deallocating memory(in destructor) to the pointer yourself. Also, You need to manage the exceptions and do the manual management of the underlying data everytime you access it.
Also you would have to ensure following Rule of Three for your class.
In short there are too many places where you can shoot yourself in the foot(or head) easily, so safest and best way is to use a std::string
as member and save yourself all the trouble.
Upvotes: 11