Demonstrates what happens when a data member with an initializer is constructed - C++ Class

C++ examples for Class:Constructor

Description

Demonstrates what happens when a data member with an initializer is constructed

Demo Code

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

class EmployeeId{
  public:/*from  w w w .  ja  v a2 s .  c  om*/
    EmployeeId(int id) : value(id){
        cout << "id = " << value << endl;
    }

  protected:
    int value;
};

int nextEmployeeId = 1000;
class Employee{
  public:
    Employee(const char *pName, int ssId): name(pName), id(ssId){
        cout << "constructing employee " << pName << endl;
    }
    Employee(const char *pName): name(pName){
        cout << "constructing employee " << pName << endl;
    }
  protected:
    string name;
    EmployeeId id = nextEmployeeId++;
};

int main(int argcs, char* pArgs[])
{
    Employee s1("tom", 1234);
    Employee s2("abc");

    return 0;
}

Result


Related Tutorials