No they're both rubbish!
Code 1 assigns to a local variable, which will be lost as soon as the constructor completes.
Code 2 is a horrible way to copy a string and doesn't take into account the null terminator, which would cause you all sorts of problems. However, it isn't a problem, because again the pointer is local and will be lost also, resulting in a memory leak.
What do you want to do? Copy a string at the constructor? Or just hold pointer to an persistent string? They are both different techniques as Sebastian says.
Try this. Set your class declaration to look like this.
Code:
class blah
{
private:
char* pCPtr;
public:
blah(char* c);
~blah();
};
Notice I've put in a char* in the private section. All methods of the class will be able to see this, and it exist as long as the object exists.
If you want to hold pointer to an external persistent string, do the following:
Code:
blah::blay(char* c)
{
pCPtr = c;
}
Here we have passed it a pointer to a character array. The constructor has assigned pCPtr to point to the same thing. There is no need to worry about freeing the char array within the blah class because it is assumed that the memory contents will be deallocated externally. What ever c points to should remain persistent for as long the blah class needs to use pCPtr. If the memory contents are freed, pCPtr would then point to an invalid address.
If you want to make a copy of the string pointed to by c, then do this:
Code:
blah::blah(char* c)
{
int len = strlen(c);
pCPtr = new char[len+1];
strcpy(pCPtr, c);
}
Notice I have created an array 1 longer than the string length. This to make room for the NULL terminator, which is how C/C++ knows where strings end.
In this case, with have created a new memory resource, and copied the contents pointed to by c into it. If the contents of c later become invalid or change, it doesn't matter because we have a seperate copy.
However, the blah object is responsible for deallocating the memory of pCPtr, because it created it. You should do this in the destructor, as follows:
Code:
blah::~blah()
{
delete[] pCPtr;
}