One constructor can invoke another constructor in the same class - C++ Class

C++ examples for Class:Constructor

Description

One constructor can invoke another constructor in the same class

Demo Code

#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;

class Employee{//  www.  ja  va2s. c o  m
  public:
    Employee(const char *pName,int xfrHours,double xSalary){
        cout << "constructing employee " << pName << endl;
        name = pName;
        workHour = xfrHours;
        salary = xSalary;
    }
    Employee() : Employee("No Name", 0, 0.0) {}
    Employee(const char *pName): Employee(pName, 0, 0.0){}

  protected:
    string  name;
    int     workHour;
    double  salary;
};

int main(int argcs, char* pArgs[]){
    Employee noName;
    Employee s2("abc");
    Employee s1("def", 80, 2.5);

    return 0;
}

Result


Related Tutorials