Conversion Operator question

B

Bill97

In my code below, the conversion operator is invoked implicitly (and
explicitly) in main(). In the first case, the address value is output--in
the later cases the character string pointed to by the address is output.

I am looking for a satisfying answer as to why the character string isn't
output in the first of the 3 cases? Thank you for your reply


class String
{
public:
String(char * s)
{
strcpy(A, s);
}

operator char *()
{
cout << "conv. op. called" << endl;
return A;
}

private:
char A[100];
};


int main()
{

String pet("cat");

cout << pet << endl;

cout << (( char *)pet) << endl;

cout << static_cast< char *>(pet) << endl;


return 0;
}
 
R

Raghu Uppalli

It is printed. Here is what I get when I run this..

conv. op. called
cat
conv. op. called
cat
conv. op. called
cat

g++ 3.4.2
 
B

Bill97

Raghu Uppalli said:
It is printed. Here is what I get when I run this..

conv. op. called
cat
conv. op. called
cat
conv. op. called
cat

g++ 3.4.2
Thanks for letting me know that. That was what I wanted to get. Using MS
Visual Studio 6.0, I got an address, followed by two cats. Conversion
operator was called all 3 times.

The only explanation I can think of is that perhaps a char* value is
converted to some type of string object (and only one conversion can be
applied).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,202
Messages
2,571,055
Members
47,659
Latest member
salragu

Latest Threads

Top