Loading....
Coupon Accepted Successfully!

 

Direct Access To Private Members

So far, we have initialized private members of the class using the constructor or member function of the same class. In the previous sub-topic, we also learned how private members of the class can be accessed using pointers. In the same way, we can initialize private members and display them. One can do this by obtaining the address of any public member variable and using the address of the object. The address of the object contains the address of the first element. Programs dealing with this are given below.
 

13.26 Write a program to initialize the private members and display them without using member functions.

#include<iostream.h>

#include<conio.h>

class A

{

private :

int x;

int y;

};

void main()

{

clrscr();

A a;

int *p=(int*)&a;

*p=3;

p++;

*p=9;

p--;

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

p++;

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

}

OUTPUT
x= 3
y= 9
 
Explanation: In the above program, a is an object of class A. The address of the object is assigned to integer pointer p by applying type casting. The pointer p points to private member x. Integer value is assigned to *p, that is, x. Address of object a is increased and by accessing the memory location value 9 is assigned to y. The p- - statement sets the memory location of x. Using the cout statement contains of x is displayed.
 

13.27 Write a program to initialize and display private members using pointers.

#include<iostream.h>

#include<conio.h>

class A

{

private :

int x;

int y;

};

class B : public A

{

public :

int z;

void show(int *k)

{

cout<<“x= ”<<*k << “ y =”<<*(k+1) <<“ z=”<<*(k+2);

}

};

void main()

{

clrscr(); // clears the screen

B b; // object declaration

int *p; // pointer declaration

p=&b.z; // address of z is assigned to p

*p=3; // initialization of z

p--; // points to previous location

*p=4; // initialization of y

p--; // points to previous location

*p=5; // initialization of x

b.show(p); // passing address of x to function show()

}

OUTPUT

x= 5 y =4 z=3

 
Explanation: In the above program, class A has two private integer member variables x and y. The class B has a one-integer variable z, and it is derived from class A. In function main(), b is an object of class B, and p is a pointer. The pointer p is initialized with the address of public member variable z. The memory location of p is initialized with 3 (initialization of z). By applying a decrease operation on pointers, previous locations are accessed, and initializations of memory locations are done (initialization of y and x). The address of x is passed to function show(). By applying an increase operation with the pointer address, the successive elements are displayed.




Test Your Skills Now!
Take a Quiz now
Reviewer Name