1

I would like to save my object name as a string. May I explain using a few lines of code.

#include <iostream>
#include <string>
#include <stdio.h>

using namespace std; 

class Example
{
public:
  string object_name;
  //code... 
};

int main()
{
  Example object;
  cout<<object.object_name<<endl; //In this case the output should be "object", how to achieve this ?
  return 0;
}
Marcello Bardus
  • 365
  • 2
  • 4
  • 13

2 Answers2

3

There is no way to access variable name from inside object, as it exist only on source code level. Best you can do, is to provide name of the object to constructor: Example object("object"), you can even wrap it in macro to avoid duplication:

#define CREATE_OBJECT(TYPE, NAME) TYPE NAME( #NAME )

CREATE_OBJECT(Example, object);

You should be vary with copying/moving objects, as it will preserve name which might not correlate to copy name. You will have do delete copy/move constructors, greatly reducing usefulness of your object, and define new constructors which take existing object and new name and create COPY_OBJECT macro for it.

Even then there is an issue with references...

TL;DR: it usually does not worth it.

Revolver_Ocelot
  • 8,609
  • 3
  • 30
  • 48
0

To get this functionality in C++, you'd have to set object_name yourself, and the only way to do that without redundantly specifying it for the Example instance and its object_name data member is to use a macro to store the "stringified" identifier:

#define EXAMPLE(IDN) Example IDN{ #IDN }

EXAMPLE(object);

That's pretty ugly IMHO: people will mistake it for a runtime function call.

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252