Functions In Structures

Structures can contain not only data but also functions, typically operating on the structure's data, but not necessarily. If you want a function to be part of a structure, you need to insert the function’s prototype within the structure's declaration:
struct Student
{
     char name[20];
     float gradeArray[5];
     void initializeArray();  // function prototype
};
while the function's implementation needs to be written outside the structure, being linked to its structure by the scope resolution operator:
void Student::initializeArray()
{
    for(unsigned int i = 0; i < 5; i++)
           gradeArray[i] = 0;
}
In case a function's code needs to be executed as fast as possible, it can be inserted in the structure's declaration:
struct Student
{
     char name[20];
     float gradeArray[5];
     void initializeArray() // function's implementation.
     {
         for(unsigned int i = 0; i < 5; i++)
                gradeArray[i] = 0;
     }
};
In such a case, the time taken to make the function call is saved, because the function is hardcoded within each structure's instance. When a function is implemented within a structure it is said to be coded inline. Inline coding should be used for very short functions, or for those functions for which fast execution is paramount. In all other cases the function's implementation should be located outside the structure, in order to avoid the duplication of the function's code (remember: when a function is coded inline each instance of a structure contains the function's implementation).

Example


#include <iostream>
#include <cstring>
using namespace std;

struct Student // MyStruct can be used to declare other structure variables
{
     char name[20];
     float gradeArray[5];
     void initializeArray();
     float average();
}; // declaration of two structure variables

void Student::initializeArray()
{
    for(unsigned int i = 0; i < 5; i++)
           gradeArray[i] = 0;
}

float Student::average()
{
    float sum = 0;
    for(unsigned int i = 0; i < 5; i++)
           sum += gradeArray[i];
    return sum/i;
}

int main()
{
    Student student1;
    student1.initializeArray();
    strcpy(student1.name, "Mike");
    student1.gradeArray[0] = 6;
    student1.gradeArray[1] = 7;
    student1.gradeArray[2] = 6.5;
    student1.gradeArray[3] = 7.5;
    student1.gradeArray[4] = 5.5;
    cout << "Grades average is : " << student1.average();
}

Output

Grades average is : 6.5