Loading....
Coupon Accepted Successfully!

 

Accessing Private Members With Pointers

In the previous topic, we learned how to access public members of a class using pointers. The public and private member variables are stored in successive memory locations. The following program explains how private members can also be accessed using pointers.
 

 

13.25 Write a program to access private members like public members of the class using pointers.

#include<iostream.h>

#include<conio.h>

class A

{

private:

int j;

public :

int x;

int y;

int z;

A()

{

j=20;}

};

void main()

{

clrscr();

A a;

int *p;

a.x=11;

a.y=10;

a.z=15;

p=&a.x;

p--;

cout<<endl<<“j =”<<*p;

p++;

cout<<endl<<“x= ”<<*p;

p++;

cout<<endl<<“y= ”<<*p;

p++;

cout<<endl<<“z= ”<<*p;

}

OUTPUT
j = 20
x = 11
y = 10
z = 15

Explanation:
 This program is similar to the previous one. In addition, the class A has one private member variable. The private member variables can be accessed using functions, and no direct access is available to them. However, using pointers, we can access them as in the case of public member variables.




Test Your Skills Now!
Take a Quiz now
Reviewer Name