The keyword typedef
The keyword typedef is in C++ allowed, but no longer necessary when it is used as a prefix in union, struct or enum definitions. This is illustrated in the following example:
When a struct, union or other compound type is defined, the tag of this type can be used as type name (this is some struct in the above example):
what.d = 3.1415;
Functions as part of a struct
In C++ it is allowed to define functions as part of a struct. This is the first concrete example of the definition of an object: as was described previously, an object is a structure containing all involved code and data. A definition of a struct point is given in the code fragment below. In this structure, two int data fields and one function draw() are declared.
struct point // definition of a screen
int x, // coordinates
y; // x/y
void draw(void); // drawing function
A similar structure could be part of a painting program and could, e.g., represent a pixel in the drawing. Concerning this struct it should be noted that:
- The function draw() which occurs in the struct definition is only a declaration. The actual code of the function, or in other words the actions which the function should perform, are located elsewhere: in the code section of the program, where all code is collected.
- The size of the struct point is just two ints. Even though a function is declared in the structure, its size is not affected by this. The compiler implements this behavior by allowing the function draw() to be known only in the context of a point.
The point structure could be used as follows:
point // two points on
a, // screen
a.x = 0; // define first dot
a.y = 10; // and draw it
b = a; // copy a to b
b.y = 20; // redefine y-coord
b.draw(); // and draw it
The function which is part of the structure is selected in a similar manner in which data fields are selected; i.e., using the field selector operator (.). When pointers to structs are used, -> can be used. The idea of this syntactical construction is that several types may contain functions with the same name. E.g., a structure representing a circle might contain three int values: two values for the coordinates of the center of the circle and one value for the radius. Analogously to the point structure, a function draw() could be declared which would draw the circle.