-1
#include<iostream>
#include<typeinfo>
using namespace std;
int main(){
    class c1{
        public:
        int a ;

    };

c1 obj1;
cout<<typeid(obj1).name();  
}

I ran it on ideone and the typeid.name() returns Z4mainE2c1. It becomes apparent that c1 is the name of the class but what is Z4mainE2. Why is it not displaying the type name only?

rimalroshan
  • 729
  • 1
  • 9
  • 25
  • 7
    https://en.wikipedia.org/wiki/Name_mangling . Note that the exact string produced by `std::type_info::name()` is not prescribed by the standard. A compiler is free to produce whatever's convenient. – Igor Tandetnik Nov 11 '17 at 01:56
  • 1
    The [`typeid`](http://en.cppreference.com/w/cpp/language/typeid) operator returns a [`std::type_info`](http://en.cppreference.com/w/cpp/types/type_info) structure whose [`name()`](http://en.cppreference.com/w/cpp/types/type_info/name) member function returns a ***implementation defined*** null terminated string. Exactly what the contents of the string will be is not specified. In your case it seems to be a *mangled* type name. – Some programmer dude Nov 11 '17 at 01:58
  • 1
    As for the actual string you get, like you said the "c1" part is easy to decipher, but so should the "main" part also be, since `c1` is defined inside the `main` function. – Some programmer dude Nov 11 '17 at 02:00
  • 2
    `4main` means the function named `main` with length of 4, `2c1` is an identifier named `c1` (length of 2). you can demangle that with many tools like [demangler.com](https://stackoverflow.com/q/3006438/995714) or [c++filt](https://stackoverflow.com/q/4939636/995714) – phuclv Nov 11 '17 at 02:10

1 Answers1

1

Z4mainE2 is the result of "name mangling". Basically, C++ compilers are designed around a linker model which doesn't directly support things like function overloading, operators, or even class members. To support the various non-C features of C++, object code produced by the compiler adds special sequences to the generated names. While the mangled names aren't generally visible or important to the programmer, the typeinfo object on some platforms exposes them directly.

Sneftel
  • 34,359
  • 11
  • 60
  • 94