Hello, I'd like to discuss a problem I've stumbled across today.
You know the typeid operator in C++. I tried using it to determine the polymorphic type of an object referred to by a base-class pointer by using the name() method of the type-id object typeid returns. Then I would be printing that name on the screen using puts(). And that's where my problem arises. Let me show you an example:
1 2 3
class MyClass { };
//...
puts( typeid(MyClass).name() );
The problem is this code would print to the screen 7MyClass instead of just the name. I soon realised the number at the beginning is the string length. Of course I did a google search and after I changed my code to use cout << stream instead of puts() the correct class name is printed. Using the printf() function gave the same result as puts().
This brings the question what exactly does this name() function return and why does cout behaves differently from puts/printf even though the function return type is const char * (a pointer to a null-terminated char array), you know the type that is more native to C functions that to C++. And how does cout know that the string length is encoded inside the string and omits it when displaying the result?
Well, not on my system. The only thing I'm doing is substitute cout << typeid(MyClass).name() << endl; with puts( typeid(MyClass).name() ); or with printf("%s\n", typeid(MyClass).name() ); And it's not the same result (read the prev. post).
I'm using the Code::Blocks compiler with GNU/GCC compiler version 4.5.2 (Ubuntu/Linaro 4.5.2-8ubuntu4)
This brings the question what exactly does this name() function return and why does cout behaves differently from puts/printf even though the function return type is const char * (a pointer to a null-terminated char array), you know the type that is more native to C functions that to C++. And how does cout know that the string length is encoded inside the string and omits it when displaying the result?
To answer your question, the text of the name function is implementation-defined, so GCC will have different output to Microsoft and so on.