Pointers to Objects

A pointer of a certain class can point to an object of that class. To access members of an object through a pointer the arrow operator -> can be used as an alternative to the combined star * and dot . operators. Further, if a member of a class is of a certain type, you can assign that member's address to a pointer of the appropriate type.

Example


#include <iostream>
using namespace std;

class AClass
{
public:
     int a;
     AClass(int x)
     {
        a = x;
     }
};
 
int main()
{
     AClass obj1(86);
     AClass *pAClass;  // pointer to AClass objects
     pAClass = &obj1;  // assign the address of obj1 to pAClass
     pAClass->a = 24;  // accessing a member variable through a
                       // pointer by using ->
     cout << obj1.a << endl;
     int* pint = &obj1.a;  // accessing a member variable
                           // through a pointer to the variable
     *pint = 4;
     cout << obj1.a;
}

Output

24
4