Replace Structure Initialization with Class Constructor



next up previous
Next: SUMMARY Up: TECHNIQUES AND EXAMPLES Previous: Explicit Default

Replace Structure Initialization with Class Constructor

 

Universally, struct should be replaced by class. One reason for this is that structure initialization provides no error checking as illustrated in the following code.

struct worker
{
    char *name;
    int age;      // must be 18 years old to work
};

wrong()
{
    struct worker child = {"Erin", 7};
}

Replacing struct worker with a class and the initialization with the appropriate constructor allows for such error checking.

class Worker
{
    char *name;
    int age;

public:
    Worker(char *initial_name, int initial_age)
    {
        if (initial_age < 18)
            labor_law_violation();
        else
        {
            age = initial_age;
            name = initial_name;
        }
    }
};

right()
{
    Worker child("Erin", 7);    // flagged as a labor_law_violation
}



David Binkley
Thu Feb 29 10:02:46 EST 1996