Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are pointers to class members used for?

Tags:

c++

oop

pointers

I have read about pointers to class members, but I have never seen them being used in any practical applications. Can someone explain what are the use cases of such pointers? Is it really necessary to have such pointers?

Eg.

class abc
{
public:
    int a;
    abc(int val) { a = val; }
};

 int main()
{
   int abc::*data;
   abc obj(5);

   data = &abc::a;

   cout << "Value of a is " << obj.*data << endl;

   return 0;
}

In the above eg. why is the value of 'a' accessed in this manner? What is the advantage of using pointers to class members?

like image 610
srikanta Avatar asked May 06 '10 05:05

srikanta


People also ask

What is the use of pointers with classes?

Pointers are used for file handling. Pointers are used to allocate memory dynamically. In C++, a pointer declared to a base class could access the object of a derived class. However, a pointer to a derived class cannot access the object of a base class.

What are pointers to pointers used for?

The first pointer is used to store the address of the variable. And the second pointer is used to store the address of the first pointer. That is why they are also known as double-pointers. We can use a pointer to a pointer to change the values of normal pointers or create a variable-sized 2-D array.

Which operator is used in pointer to member?

There are two pointer to member operators: . * and ->* . The . * operator is used to dereference pointers to class members.


2 Answers

The biggest advantage of a pointer-to-member or pointer-to-member-function is that you

  • don't have to bind to a specific instance right away
  • don't need to place any restrictions on the member names, only the type has to match.

This can be used for e.g. call-backs or abstract algorithms:

std::map<int,int> m;
m.insert(std::make_pair(1,2));
m.insert(std::make_pair(3,4));
m.insert(std::make_pair(5,6));
std::ptrdiff_t s = 
    std::count_if(m.begin(), m.end(),
                  boost::bind(&std::map<int,int>::value_type::first, _1) > 2);
std::cout << s << std::endl; // 2

Note that Boost.Bind, Boost.Function and their TR1 equivalents already encapsulate that nicely for you. To a certain degree the current standard also includes tools like std::mem_fun in <functional>.

like image 85
Georg Fritzsche Avatar answered Oct 25 '22 09:10

Georg Fritzsche


If you have used MFC, you will see pointers to member function concept is heavily used (internally)

DECLARE_MESSAGE_MAP, BEGIN_MESSAGE_MAP, END_MESSAGE_MAP See Message Maps

like image 24
SysAdmin Avatar answered Oct 25 '22 09:10

SysAdmin