We can have pointers to object. When accessing members of a class given a pointer to an object, we use the arrow (→) operator instead of dot operator.
Just like pointers to normal variables and functions, we can have pointers to class member functions and member variables.
Defining a pointer of class type:
We can define pointer of class type, which can be used to point to class objects.
class Simple //Simple is the class name
{
public:
int a;
};
int main()
{
Simple obj;
Simple* ptr; // Pointer of class type
ptr = &obj;
cout << obj.a;
cout << ptr->a; // Accessing member with pointer
}
Here we can see that we have declared a pointer of class type which points to class’s object. We can access data members and member functions using pointer name with arrow -> symbol.
________________________________________
Pointer to Data Members of class
We can use pointer to point to class’s data members (Member variables).
Syntax for Declaration:
datatype class_name :: *pointer_name ;
Syntax for Assignment:
pointer_name = &class_name :: datamember_name ;
Both declaration and assignment can be done in a single statement too.
datatype class_name::*pointer_name = &class_name::datamember_name ;
Using with Objects
For accessing normal data members we use the dot . operator with object and -> qith pointer to object. But when we have a pointer to data member, we have to dereference that pointer to get what its pointing to, hence it becomes,
Object.*pointerToMember
and with pointer to object, it can be accessed by writing,
ObjectPointer->*pointerToMember
Example:.
class Data
{
public:
int a;
void print() { cout << "a is="<< a; }
};
int main()
{
Data d, *dp;
dp = &d; // pointer to object
int Data::*ptr=&Data::a; // pointer to data member 'a'
d.*ptr=10;
d.print();
dp->*ptr=20;
dp->print();
}
Output: a is=10 a is=20