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
?
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
?
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.
Where A is class
typeid(A).name()
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
.