Coupon Accepted Successfully!


Pointers and Inheritance

The private and public member variables of a class are stored in successive memory locations. A pointer to a public member variable gives us access to private member variables.
The same is true for the derived class. The member variables of the base and derived classes are also stored in successive memory locations. The following program explains the mechanics of accessing private data members of the base class using the address of public member variables of the derived class using pointers. Here, no member functions are used.

11.30 Write a program to access private member variables of base class using pointers
Address of z : 65524 Value of z :3
Address of y : 65522 Value of y :2
Address of x : 65520 Value of x :1

Explanation: In the above program, class A contains two private member variables x and y. The constructor initializes the member variables. The class B is derived from the class A. The class B has one public member variable. In function main(), b is an object of class B. The pointer p is an integer pointer. The address of the member variable z of the derived class B is assigned to the pointer p. By applying a decrease operation, we get the previous memory locations where the member variables of the base class are stored. The values of all member variables are displayed along with their addresses.

Test Your Skills Now!
Take a Quiz now
Reviewer Name