P
Phil Ward
The following has recently arose and it is the first time I have noticed
this behaviour.
I have been using a self-defined string class. It's form is
class CMyString
{
public:
... (no public varaibles)
...
operator char* () const { return mpChar; }
private:
char* mpChar;
unsigned long mBytesAllocated;
};
Obviously the purpose of the casting operator is to be able to use the
object much like a null terminated c-string.
The following code is ok:
char Buff[100];
CMyString MyString("Hello");
strcpy(Buff, (char*) MyString);
Something interesting happens if the cast operator is (accidently) omitted.
strcpy(Buff, MyString);
This code compiles and links without warning. Lint does warn that the second
argument is not a pointer.
However, this code executes and Buff end up with the value "Hello". It
appears that the object name is interpreted
as a pointer to the mpChar private data member. If the specificiation order
of mpChar and mBytesAllocated
is reversed, the code again compiles and links but will crash on execution.
My conclusion is that the name of an object is a pointer to the first(?)
class data member. I have never seen this
mentioned in the literature. Is this common knowledge and I have just missed
it? I would not have immediately
caught this without lint and, in some ways, it appear dangerous.
Thanks for any comments.
Phil Ward
this behaviour.
I have been using a self-defined string class. It's form is
class CMyString
{
public:
... (no public varaibles)
...
operator char* () const { return mpChar; }
private:
char* mpChar;
unsigned long mBytesAllocated;
};
Obviously the purpose of the casting operator is to be able to use the
object much like a null terminated c-string.
The following code is ok:
char Buff[100];
CMyString MyString("Hello");
strcpy(Buff, (char*) MyString);
Something interesting happens if the cast operator is (accidently) omitted.
strcpy(Buff, MyString);
This code compiles and links without warning. Lint does warn that the second
argument is not a pointer.
However, this code executes and Buff end up with the value "Hello". It
appears that the object name is interpreted
as a pointer to the mpChar private data member. If the specificiation order
of mpChar and mBytesAllocated
is reversed, the code again compiles and links but will crash on execution.
My conclusion is that the name of an object is a pointer to the first(?)
class data member. I have never seen this
mentioned in the literature. Is this common knowledge and I have just missed
it? I would not have immediately
caught this without lint and, in some ways, it appear dangerous.
Thanks for any comments.
Phil Ward