Archive for the ‘Differences between C and C++’ Category

Functions as part of a struct

March 8th, 2010 c# No comments

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 (see section 2.4), 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
{                       // dot:
x,              // coordinates
y;              // x/y
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. We will describe the actual definitions of functions inside structs later

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.