16.7 POINTERS TO MEMBERS

We have seen that pointers pointing to various types are considered belonging to separate types. Consider a case where we have a member of a class of type int. Will it be safe to point to this member with ordinary pointer? The answer is obviously no. Hence, C++ has defined a separate syntax for pointes to members (both data members and methods).

Pointer to data member

Two operators, namely (.*) and (->*) are designed for this purpose. Consider a class Date. Let it have a member of type int. If we want to declare a pointer to it we have to first declare as follows.

    int Date::* ptrl =&Date::year;

This declaration defines a pointer ptr1. It points to data member of class Date. If you observe the declaration carefully, ...

Get Object Oriented Programming with C++, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.