1

Suppose I have a class as

class A {
  char a[15], b[11],c[17];
public:
  void names();

}
void A :: names() {
   char x[20];
   x=a;
   cout<<x;
   x=b;
   cout<<x;
   x=c;
   cout<<x;
} 

I want to copy data in x from each member of A one by one and use a for loop to represent the member names. is there a way in which I can store them? So something like-

    void A :: names() {
           char x[20];
           while(all members of A not traversed){
                 x=current member;
                 cout<<x;
                 update member;
          }
    }
  • Can you clarify what you want? The question is not clear. – Joseph Thomson Mar 21 '17 at 08:37
  • @Svaberg Thanks for the link – Tanisha Shrotriya Mar 21 '17 at 13:49
  • @Joseph Thomas I will update my question, to clarify. Please do refer. – Tanisha Shrotriya Mar 21 '17 at 13:52
  • @TanishaShrotriya Reflection is not part of the C/C++ language, see e.g. [how can I add reflection to a c application](http://stackoverflow.com/questions/41453/how-can-i-add-reflection-to-a-c-application). If you just want to store (key, value)-pairs, use a [map](http://en.cppreference.com/w/cpp/container/map). This will be a lot easier. – Svaberg Mar 23 '17 at 03:23

2 Answers2

1

Sounds like you want to iterate through a class's members. Like

for (variable in a's members) {
    a.x append variable's value
}

There is no trivial methods to iterate through a class's members. You should use a map instead, which provide iteration features among keys.

for (auto const& x : the_map) {
    x.first  // name or key
    x.second // value
}
xhg
  • 1,850
  • 2
  • 21
  • 35
0

The idiomatic way to do this in C++ is through pointers.

class A {
  char a[15], b[11],c[17];
  char *members[3] = {a, b, c}; // valid only for c++11 or above
public:
  void names();
};

void A::names() {
    for (char *x: members) {  // c++11 range loop...
        cout << x << endl;
    }
}

But except if you have strong reasons to use raw char arrays, std::string is generally simpler to use...

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252