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?
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.
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.
There are two pointer to member operators: . * and ->* . The . * operator is used to dereference pointers to class members.
The biggest advantage of a pointer-to-member or pointer-to-member-function is that you
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>
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With