Addresses Of Objects And void PointersThe 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:
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.