operator const char*

Why that the function c_str and operator const char* didn't return the same value in this code ?



#include <iostream>

usingnamespace std;

class MyString
{
char* buffer;
int length;

public:
MyString(constchar* pChaine);
~MyString();

constchar* c_str()const;
operatorconstchar*()const;
};

MyString::MyString(constchar* pChaine)
{
length = strlen(pChaine);
buffer =newchar[length + 1];

strcpy(buffer, pChaine);
}

MyString::~MyString()
{
if (buffer != NULL)
delete[] buffer;

length = 0;
}

constchar* MyString::c_str()const
{
return buffer;
}

MyString::operatorconstchar*()const
{
return buffer;
}

int main()
{
MyString s1("Hello");

cout << s1.c_str() << endl;
cout << s1 << endl;

return 0;
}


Return value:

Hello
003207A8 (adress of buffer)

Thanks

[2058 byte] By [cro] at [2008-2-17]
# 1
This test was done under Visual Studio C++ 6. I have try it with Visual Studio 2003 and it work. So, How can this work under Visual Studio 6 ?

Thanks

cro at 2007-9-8 > top of Msdn Tech,Visual C++,Visual C++ Language...
# 2

I tested it in VS6 and VS 2005 Beta2. The behaviour you stated is observed.
operator const char* () const returns the pointer to the buffer as might be expected. It looks like the iostream functions in VS2003 and VS2005 are a bit civilized. May be some one will tell us for sure.

But you can do as follows to make it work in VC6 (since u ask how to make it work as you want).

int main()
{
MyString s1(
"Hello");
cout << s1.c_str() << endl;
cout <<(
const char*)s1<<endl;

//or this
printf(s1);

return 0;
}

Tesfaye at 2007-9-8 > top of Msdn Tech,Visual C++,Visual C++ Language...
# 3
In fact, what I whant is that the operator work. Otherwise, I would have used the c_str function. At least I know that it is not my Visual Studio that is going weird.
cro at 2007-9-8 > top of Msdn Tech,Visual C++,Visual C++ Language...