How to Access Classes Members through Pointers in C++


It is possible to assign the address of the members of a class and assign it to pointers. We can use pointers to access the data members of a class if that pointer has the data type which is same as the class type. The address of the data member of the class can be obtained using the & operator.

The class member pointer should be declared using the * operator. In order to refer directly to a member of an object pointed by a pointer, we can use here the arrow operator (->) of indirection in C++.

C++ Program For Accessing Classes Members through Pointers

#include<iostream> using namespace std; class Sample{ int a; public: void read(){ cout<<"Enter a number :"; cin>>a; } void print(){ cout<<"\n The entered value is :"<<a<<endl; } }; int main(){ Sample s, *p; p= &s; s.read(); p->print(); return 0; }

Output:-

Enter a number : 29
The entered value is :29

Explanation of the program

In this program, p is a pointer which is the class type Sample. The pointer p points to the address of the object Also, the pointer p can access the printf() function directly and freely.