Inside FileTwo.h
#include"iostream"
using namespace std ;
class FileTwo{
public:
FileTwo(){
cout<<"constructor for";//Here want to show the object for which the constructor has been called
}
~Filetwo(){
cout<<"Destructor for ";//Here want to show the object for which the destructor has been called
};
Inside main.cpp
#include"Filetwo.h"
int main(){
FileTwo two ;
return 0;
}
I know this sample program is very small , so we can able to find out the object for which the constructor and destructor has been called . But for big project is there any way to know the object name ? Thanks in advance .
It is possible. If your compile supports
__PRETTY_FUNCTION__or__func__(see this), then you can do this:Note that I’ve also printed to
cerrto ensure that this output gets flushed immediately and isn’t lost if the program crashes. Also, since each object has a unique*thispointer, we can use that to see when particular objects are being made or getting killed.The output for the above program on my computer is:
Note that
__func__is a C99 standard identifier. C++0x adds support in the form of an “implementation-defined string”.__FUNCTION__is a pre-standard extension supported by some compilers, including Visual C++ (see documentation) and gcc (see documentation).__PRETTY_FUNCION__is a gcc extension, which does the same sort of stuff, but prettier.This question has more information on these identifiers.
Depending on your compiler, this may return the name of the class, though it may be a little mangled.
If you are trying to get the name of the variable to which the class is instantiated (
twoin your case), then there is not, to my knowledge, a way to do this. The following will emulate it: