1

In Java, if I want to use the object class' name I can write:

String myString = this.getClass().getSimpleName();

What's the C++ equivalent of this? That is, how can I get a string with the name of the class of *this?

einpoklum
  • 118,144
  • 57
  • 340
  • 684

3 Answers3

5

There is no equivalent in standard C++. The closest you'll get is typeid(*this).name(), but there's no guarantee about what the "name" will look like - the result is implementation-defined. It will basically be whatever your compiler decided to put there, which may or may not correspond to the class's name in the source code. See cppreference.com for more information.

If you want to know the name of a class whose code you can change, you could write a function that returns a readable name. But otherwise, you're basically stuck with whatever the code above returns.

cHao
  • 84,970
  • 20
  • 145
  • 172
  • @einpoklum: `name()` returns an *implementation-defined* name. Which basically means it could be anything; it need not even be human-readable or unique. See http://en.cppreference.com/w/cpp/types/type_info/name for more info. – cHao Jan 01 '14 at 10:34
1

Where A is class

typeid(A).name()
Digital_Reality
  • 4,488
  • 1
  • 29
  • 31
0

We can Create our own Function For that,

class ClassName
{ 
     static std::string const className() 
     { 
         return "ClassName"; 
     }
};
std::string const name = ClassName::className();

The QObject->metaObject() method is valid for Qt except the QGraphicsItem based classes that not inherit from QObject.

Rakesh KR
  • 6,357
  • 5
  • 40
  • 55
  • Of course the whole point is to avoid the need to implement this method for every class... – einpoklum Jan 01 '14 at 10:25
  • For C++11 you might be able to make use of the `__func__` macro inside the class constructor to save the class name somewhere specific so that your generic className() member function will work. In the constructor `__func__` obviously will expand to the name of the class – Brandin Jan 01 '14 at 11:09