I am trying to access member variables of a class without using object. please let me know how to go about.
class TestMem
{
int a;
int b;
public:
Tes
There totally is a way. C++ has member pointers, pointers relative to an object. They are defined by prefixing T::
to the *
on the pointer type, and used by using the ->*
or .*
member pointer access operators. So yeah, it looks horrible :).
class T {
int a, b;
public:
typedef int T::* T_mem_ptr_to_int;
static T_mem_ptr_to_int const a_ptr;
static T_mem_ptr_to_int const b_ptr;
};
T::T_mem_ptr_to_int const T::a_ptr = &T::a;
T::T_mem_ptr_to_int const T::b_ptr = &T::b;
int weird_add(T* left, T* right) {
return left->*T::a_ptr + right->*T::b_ptr;
}
This is used much more often for member function pointers, which look like Result (T::*ptr_name)(Arg1, Arg2, ...)
.