A class may pass along arguments to the members' constructors - C++ Class

C++ examples for Class:Constructor

Description

A class may pass along arguments to the members' constructors

Demo Code

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

int nextEmployeeId = 1000; // first legal Employee ID
class EmployeeId// w  w  w .ja  v  a2s  . c  om
{
  public:
    EmployeeId(){
        value = nextEmployeeId++;
        cout << "Take next employee id " << value << endl;
    }
    EmployeeId(int id){
        value = id;
        cout << "Assign employee id " << value << endl;
    }
  protected:
    int value;
};

class Employee
{
  public:
    Employee(const char* pName)
    {
        cout << "constructing Employee " << pName << endl;
        name = pName;
        workHour = 0;
        salary = 0.0;
    }
  protected:
    string    name;
    int       workHour;
    double    salary;
    EmployeeId id;
};

int main(int argcs, char* pArgs[])
{
    Employee s1("Jack");
    Employee s2("Tom");

    return 0;
}

Result


Related Tutorials