Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the list of member variables of a class and their types?

I haven't ever heard it's possible, but asking with the hope that it might.
For a class with many more member variables than this:

class A
{
 public:
  SomeOtherClass* s;
  int i;
  int j;
  A() {}
  A(const A& soc): s(soc.s->Clone()), i(soc.i), j(soc.j) {}
};

I always have to remember that if I add another variable int k to the class, I'll also have to add it in the initialization list k(soc.k) and sometimes in the destructor too. I've had to add/remove member variables so many times and it's really annoying to forget about the copying in the initialization list and finding the omission much much later while debugging.

Therefore, I wanted to know if there's a syntax/logic through which I can find out the list of member variables of a class and their types, so that I can maybe iterate through them and decide which of them need to be copied in the copy ctor and which of them need to be deep copied?

I don't see why the creators of C++ couldn't have included such a facility, since except for virtual members, the memory locations of variables would be contiguous and their types are known too. Even if they were extern or virtual, the type and size would be known at runtime. So shouldn't it be possible?

like image 531
Nav Avatar asked Jun 17 '11 13:06

Nav


1 Answers

There is no reflection in C++, so you'll need an external library to do this. The creators of C++ didn't implement this feature because it implies a performance penalty, and performance is one of C++'s main goals.

like image 78
dario_ramos Avatar answered Sep 22 '22 23:09

dario_ramos