Overloaded Constructors

Classes typically provide multiple constructors. This allows the users (clients) to initialize objects in several different ways.
class Employee          
{
  public:              // these functions are visible
    void setName(char first[], char last[]);
    void setSalary(float newSalary);
    void setYears(int numYears);
    void display(void) const;

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

      // another constructor (overloaded function)
    Employee(char first[], char last[], 
             float salary, int years);

  private:             // these members are not visible
    char firstName[10]; 
    char lastName[12];  
    float salary;       
    int years;          
};
The compiler can tell which constructor to use:
// matches first constructor above
Employee clerk1("Jane", "Doe");

// matches second constructor above
Employee clerk2("John", "Smith", 40000.0f, 12);

// compiler error, no constructor provided
Employee clerk3;
Previous page
Next page

Back to Index
Back to Outline