Turn the name of a variable into a string.

Hi everybody,

I am typing a public function member of a class that writes its content i.e. value of the variables etc. into a file. I would like the file to contain the object name. Is there a way to cast it?

In other words, I would like my code to look like:

class Animal {

...

public:
void WriteToFile(ofstream * OutPutFile);

};

main(){

Animal Dog;

...

dog.WriteToFile(FileName);

}

and my output file look like ...

------------------------------------------

...

Animal: Dog.

(and then all the data)

...

------------------------------------------

I can cast 'Animal' using typeid().name() but I can't find a way to cast Dog.

Thanks !
Variable names are for programmer's reference only and are not [necessarily] included in part of the compiled program. So there's no real way to do this.

You'll have to have a name as part of the class:

1
2
3
4
5
6
7
8
9
10
11
12
13
class Animal
{
  std::string name;

//...
};

int main()
{
  Animal Dog("Dog");

  //...
}
I think there might be special compilers that can embed the variable name into the compiler, but that seems over-complicated to me. Just type the name of the variable =P
"Animal" is already a class just make a member function to write the variable to a file that automatically prepends the variable name. That way you wite it once and forget about it.
Very useful !!
many thnks to both !

Where can I learn more about what compilers include and not?
ejemmm... I meant many thanks to all,
Topic archived. No new replies allowed.