We can have pointers to other types of variables; you can have pointers to objects. When accessing members of a class given a pointer to an object, use the arrow (–>) operator instead of the dot operator.
This program illustrates how to access an object given a pointer to it:
#include
using namespace std;
class cl
{
int i;
public:
cl(int j)
{
i=j;
}
int get_i( )
{
return i;
}
};
int main( )
{
cl ob(88), *ptr;
ptr = &ob; // get address of ob
cout << ptr->get_i(); // use -> to call get_i()
return 0;
}
OUTPUT: – 88. As we know, when a pointer is incremented, it points to the next element of its type. For example, an integer pointer will point to the next integer. In general, all pointer arithmetic is relative to the base type of the pointer. The same is true of pointers to objects. For example, this program uses a pointer to access all three elements of array ob after being assigned ob’s starting address:
#include
using namespace std;
class cl {
int i;
public:
cl( )
{ i=0;
}
cl(int j)
{ i=j;
}
int get_i()
{
return i;
}
};
int main( )
{
cl ob[4] = {1, 2, 3,4};
cl *ptr;
int i;
ptr = ob; // get start of array
for (i=0; i<4; i++) {
cout << p-> get_i() << "\n";
p++; // point to next object
}}
OUTPUT: 1, 2, 3,4.We can allocate the address of a public member of an object to a pointer and then access that member by using the pointer. Another example-
#include
using namespace std;
class cl {
public:
int i;
cl(int j)
{
i=j;
}
};
int main()
{
cl ob(1);
int *ptr;
ptr = &ob.i; // get address of ob.i
cout << *ptr; // access ob.i via p
return 0;
}
OUTPUT: 1 Because ptr is pointing to an integer, it is declared as an integer pointer. It is irrelevant that i is a member of ob in this situation.