Pointer to Members in C++ Classes

Pointer to Members in C++ Classses

Pointer is an important feature of C++. We can use pointers in a number of ways. In object oriented programming, sometimes we need to have pointers to objects of a class or pointer to the members of a class. This article describes this feature of C++.

Class Type Pointer

Class type pointer is used to point to object of a class. It stores the address of the object and afterwards allows us to access its members through -> operator as shown in the following code.

Class Type Pointer

In the above code, class type pointer is defined at line 24 which store the address of the object p of class Person. Once the address of the object is stored, then we can access the members of the object through the pointer as shown at line 26 to 28 above.

Pointer to Class Data Members

We can also define a pointer in order to point to a data member of a class. The following code shows that how this type of pointer can be declared and used.

Pointer to Class Data Members

In order to declare the pointer, we need to mention the data type of the data member, class name, pointer variable and the data member to which the pointer will point to, e.g.

int Person::*ptr1=&Person::age;   // pointer to data member age

In the above code, pointer *ptr1 is declared at line 25 which points to a data member ‘age’. At line 16, pointer *ptr2 is declared which points to another data member ‘name’.  Once the pointer to data member is set then we can access the data member through pointer as shown at lines 27 and 28 above. The output of the above code is as below.

lines 27

Pointer to Class Member Functions

Although this feature of C++ is not commonly used among object oriented programmers but is very useful and powerful aspect of programming. If we want to define a pointer in order to point to the member function of a class then we need to follow the following syntax.

return_type (class_name::*ptr_name) (argument_type) = &class_name::function_name ;

The following example demonstrates the use of this syntax.

Pointer to Class Member Functions

In the code above, pointer to member function is defined at line 26. While defining the pointer, we need to mention the return type, class name, pointer variable, arguments type and the name of the member function to which the pointer will point.

Once defined then we can access the member function through defined pointer as shown at line 28. The code shows that the member function can be called directly through the object of the class (line 24) or through the pointer (line 28) as well. The result will be same as shown in the following figure.

result

More Related Articles For You

    C++ Tutorial

    C++ Quizzes