Accessing of the Variables pointed to by the Pointer
Accessing of the variable pointed to by the pointer needs to be understood from two angles, i.e.,
- Accessing of normal basic data-type variables
- Accessing of class-type objects
- Accessing of normal basic data-type variables:
Let us straight-away learn the accessing of normal basic data-type (lineint
,float
, etc.) variables by seeing a simple example as follows:int *p; int x; x = 20; p = &x; //read as assign address of x (&x) to pointer variable p cout << *p; //read as print content at pointer variable p
The statement:
cout << *p;
prints the value 20 because
*p
means the value at the address p.Similarly:
*p = *p + 10
is same as:
x = x + 10;
Note that if we write the following statement:
cout << p;
this prints the address of x. Similarly the statement:
cout << &x;
also prints the addresss of x.
- Accessing the class-type objects (Pointer to Object):
Now, let us understand in brief about accessing of members of an object pointed to by a pointer.Just as you can have pointers to other types of variables, you can have pointers to objects too. When accessing members of a class given a pointer to an object, use the arrow->
operator instead of the dot operator. The operator looks like an arrow and is formed from a “minus sign” and a “greater than” symbol.The following program illustrates how to access an object given a pointer to it:
#include <iostream.h> class c1 { private: int i; public: c1(int j) { i = j; } int get_i() { return i; } }; int main() { c1 ob(88), *p; p = &ob; //get address of ob cout << p -> get_i(); //use -> to call get_i() }