0

Is there a way to instantiate an object and have a string member take the object's name? I would also not mind for a gcc builtin.

Here's an example:

#include <string>
    
class A
{
    std::string obj_name_ = /* set to the objects name (very_descriptive_name) somehow */ ;
};
    
A very_descriptive_name; // naming the *object* should be enough, do we really have to initialize the string with exactly the same name?

The string is later used for recognisability.

8
  • 1
    the name of a variable != name of an object. Consider that you can do A& a_completely_different_name = very_descriptive_name;, now the two refer to the same object via completely different names. You can do A a("very descriptive name"); Commented Apr 2, 2022 at 14:15
  • I'm not sure to understand your point. Couldn't you add a member function returning to string very_descriptive_name.str()? Commented Apr 2, 2022 at 14:17
  • stackoverflow.com/a/469108/7157435 This might help you Commented Apr 2, 2022 at 14:27
  • @463035818_is_not_a_number: I know you can do that but that's an extra step. I want the member string to be infered from from the object name Commented Apr 2, 2022 at 15:08
  • @Bob_: I don't think you understand the point. I wanted to create an object which takes its object expression name and initializes a string member with it. Commented Apr 2, 2022 at 15:09

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.