A typeid problem

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?
Last edited on
Using C++ streams gives me the same result you're getting with printf(), so I don't know what you're doing.
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)
closed account (1vRz3TCk)
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <cstdio>
#include <typeinfo>

class MyClass { };

int main()
{
    puts( typeid(MyClass).name() );
    std::cout <<  (typeid(MyClass).name()) << std::endl;
    printf("%s\n", typeid(MyClass).name() );
}


for VS2010:
class MyClass
class MyClass
class MyClass


for Code::Blocks (with GCC)
7MyClass
7MyClass
7MyClass


Tanatos wrote:
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.
Last edited on
Topic archived. No new replies allowed.