Reputation:
is there a way to let the constructor of the object know its name?
I would like to have string myObject.name created by the constructor based on the actual name of the object. Is it possible?
myClass Example;
//constructor creates an object with this name and i would like to have Example.name=="Example";
Thank you for your help!
Upvotes: 0
Views: 52
Reputation: 6707
Not very useful, but with a macro you can achieve something near:
#define CREATE( a, b ) a b(b)
int main()
{
CREATE( myClass, example );
}
assuming of course that myClass
has a constructor with a string as argument.
On the bottom line, I agree with the other answer, there really no point doing this.
Upvotes: 0
Reputation: 2272
There is no such inbuilt functionality. Although you can build one for yourself, following is the one way how you can achieve it.
class myClass {
std::string m_objectName;
public:
myClass(std::string name):m_objectName(name);
std::string name()
{
return m_objectName;
}
};
Now create object like this:
myClass Example("Example");
Upvotes: 2
Reputation: 146968
There's no guarantee that it actually has a source name of any kind, so there's no sense in such a mechanism. And furthermore, tying your user display to the internal implementation details of your source code is a tremendously bad idea.
You, of course, can assign it whatever name you like that you think has whatever meaning you like.
Upvotes: 3