0

how to print variable from value of other variable in c++ i'm just new in c++.

in php we can make/print a variable by the value of other variable. like this.

$example = 'foo';
$foo = 'abc';
echo ${$example}; // the output will 'abc'

how can i solve this in c++?

Indra
  • 436
  • 4
  • 14
  • 1
    C++ doesn't have this feature (which is reflection): http://stackoverflow.com/questions/2911442/access-variable-value-using-string-representing-variables-name-in-c – wkl May 10 '12 at 04:18

3 Answers3

3

You cannot.

The only way to emulate this (well sort of) is to use a map

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
1

Getting a variable/member by its name is called reflection/introspection.

There is no reflection mechanism in C++, and basically you can't do that.

MByD
  • 135,866
  • 28
  • 264
  • 277
0

Looking at it another way, it's just indirection, which C++ uses extensively. An analogous example in C++ might be...

using namespace std;
string foo = "abc";
string* example = &foo;
cout << *example << endl;  // The output will 'abc'

...or using a reference instead of a pointer...

using namespace std;
string foo = "abc";
string& example = foo;
cout << example << endl;  // The output will 'abc'
aldo
  • 2,927
  • 21
  • 36