Initializing Class Objects

Currently, when we instantiate a new object, its data members are undefined:
Employee clerk;  // firstName, lastName, salary, years
                 //  are all undefined at this point;
                 //   random values in memory
We need a way to initialize these members to some valid value when we create the object. To do this, we provide a constructor:
class Employee           // Employee is a new type
{
  public:                // these functions are visible
    void setName(char first[], char last[]);
    void setSalary(float newSalary);
    void setYears(int numYears);
    void display(void) const;

    // this is a constructor for the Employee class
    Employee(char first[], char last[]);

  private:               // members are not visible
    char firstName[10];  // first name is a char array
    char lastName[12];   // last name is char array
    float salary;        // yearly pay is float
    int years;           // years of service
};
A constructor is a special member function. It has no return type and it is called implicitly when you instantiate a class object:
// Employee(char first[], char last[]) is called 
Employee clerk("Jane", "Doe");
Previous page
Next page

Back to Index
Back to Outline