Coupon Accepted Successfully!


Addresses Of Objects And void Pointers

The size of an object is equal to the number of total member variables declared inside the class. The size of the member function is not considered in the case of objects. The object itself contains the address of first member variables. By obtaining the address, we can access the member variables directly, irrespective of whether they are private or public. The address of the object cannot be assigned to the pointer of the same type. This is because an increase operation on pointers will set the address of the object according to its size (size of object = size of total member variables). The address of the object should be increased according to the basic data type. To overcome this situation, a void pointer is useful. The type of void pointer can be changed at run time using type-casting syntax. Thus, all the member variables can be accessed directly. Consider the following program:

13.28 Write a program to declare void pointers and access member variables using void pointers.




class A



int x;

int y;


class B : public A


public :

int z;



x=10; y=20; z=30;



void main()


clrscr(); // clears the screen

B b; // object declaration

int j; // declaration of integer j

void *p=&b; // declaration & initialization of void

for (j=0;j<3;j++) // for loop executed for three times

printf (ā€œ\n member variable [%d] = %dā€,j+1,*((int*)p+j));

// cout<<j+1<<ā€œ ā€ <<*((int*)p+j)<<endl;


member variable [1] = 10
member variable [2] = 20
member variable [3] = 30
Explanation: In the above program, the b is an object of the derived class B. The address of the object b is assigned to the void pointer p. Using the for loop and the type-casting operation, integer values are accessed. The address of the void pointer is increased by two bytes. Thecout statement now and then will not display the result accurately, and, hence, the printf() statement is used.
The type-casting operation is done according to the data type of member variables. Here, all the class-member variables are of integer type. In any case, the class contains variables of integer, float, and char type. Thus, it is necessary to type cast according to the sequence of the member variables.

Test Your Skills Now!
Take a Quiz now
Reviewer Name