Bharat Banate's Work Profile

View Bharat Banate's profile on LinkedIn

Thursday, June 19, 2008

C++: void pointers

The keyword 'void' can be used to define a pointer to a generic term. In C++, special care has to be taken to handle the assignment of void pointers to other pointer types. Following code shows the same:

void *p;
char *s;
p = s;
s = p;

Here, the second assignment would flag an error indicating a type mismatch. While you can assign a pointer of any type to a void pointer, the reverse is not true unless you specifically typecast it as shown below:

s = (char*) p;


C++: Anonymous unions and enums

An anonymous union does not have a union name (tag) and its elements can be accessed directly without using a union variable.
For example,

union {
int i;
char ch[2];
};

Both i and array ch[] share the same memory locations and can be accessed directly simply by saying

i = 10;
ch[0] = 'A';

Simply omitting the union name in declaration does not make the anonymous union. For an union to qualify as an anonymous union, the declaration must not declare a variable of the union type.

Similarly, we can build anonymous enums as shown below:

enum {first, second, third};
int position = second;

The stream I/O classes define several anonymous enumerated types.