Question:
how to get object name in c++?
Sant
2007-11-29 02:10:58 UTC
hi ,

i am trying to get the object name, see the code below, but not able to find method, what could be the code in place of ???????.

#include "iostream"
using namespace std;
class A{
public:
int i;
void printObjectname(){
cout << ????????;//<--what could be here, to print the object name as 'objectA'
}
};

int _tmain(int argc, _TCHAR* argv[])
{
A *objectA = new A();
objectA->printObjectname();

return 0;
}
Three answers:
Big John Studd
2007-11-29 05:41:12 UTC
include the header file and use function typeid()



http://publib.boulder.ibm.com/infocenter/pseries/v5r3/index.jsp?topic=/com.ibm.xlcpp8a.doc/language/ref/the_typeid_operator.htm
cruppstahl
2007-11-29 03:00:48 UTC
Sorry, there's no such thing in C++. You have to do this manually, i.e. change the code in every class:



virtual void printObjectname() { cout "A"; }



or even better:

virtual const char *getClassname() { return "A"; }



make the function virtual, then it can be overwritten in inherited classes.
Shariq (http://coinsindia.info)
2007-11-29 03:22:32 UTC
You have read the documentation of C++.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...