user4832705
user4832705

Reputation:

Name of the object C++

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

Answers (3)

kebs
kebs

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

Hemant Gangwar
Hemant Gangwar

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

Puppy
Puppy

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

Related Questions