C++ Pointer to members
This is possible to take the address of a member of a class and assign it to a pointer. The address of a member can be obtained by applying the ampersand operator & to a “fully qualified” class member
name. A class member pointer can be declared using the operator ::* with the class name
for example given the class
class X
{
:
m;
:
show();
};
|
we can define a pointer to member m as follows:
int X::* ip=&X::m;
|
The ip pointer create thus acts like a class member in that it must be invoked with a class object.
in the statement above the phrase X::* means “pointer to pointer of X class “The phase &X::m means the “address of the m member of X class”
Note that the following statement is not valid
It is because m is not simply an int data type. it has meaning only whenever it is associated with the class to which it belongs. The scope resolution operator must be applied to both the pointer and the member.
The pointer ip can now be used to access the member m inside member functions(or the friend functions) let us assume that x is an object of X declared in a member function.
We can access m using the pointer ip as follows
cout << x.*ip;
cout << x.m;
now look at the following code
ap=&&x;
cout << ap->*ip;
cout << ap->m;
|
The dereferencing operator ->* is used to access a member when we use pointers to both the object and the member. The dereferencing operator .* is used when the object itself is used with the member pointer.
Note that *ip is used like a member name
Let us take example the use of dereferencing operators to access the class members
DEREFERENCING OPERATORS
<iostream>
using namespace std;
class M
{
x;
y;
:
set_xy(a, b)
{
x=a;
y=b;
}
friend sum(M m);
};
sum(M m)
{
M::*px=&M::x;
M::*py=&M::y;
M *pm=&m;
s=m.*px+pm->*py;
s;
}
main()
{
M n;
(M::*pf)(int,int)=&M::set_xy;
(n.*pf)(10,20);
std::cout<<"sum=" <<sum(n)<<"\n";
M *op=&n;
(op->*pf)(30,40);
std::cout<<"sum="<<sum(n) <<"\n";
}
|