Demonstrate that the default copy constructor invokes the copy constructor for each member - C++ Class

C++ examples for Class:Constructor

Description

Demonstrate that the default copy constructor invokes the copy constructor for each member

Demo Code

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

class Employee//from w w w  .j ava  2s  .c  o m
{
  public:
    Employee(const char *pName = "no name", int ssId = 0) : name(pName), id(ssId){ 
        cout << "Constructed "  << name << endl; 
    }

    Employee(Employee& s) : name("Copy of " + s.name), id(s.id){ 
        cout << "Constructed "  << name << endl; 
    }

    ~Employee(){ 
        cout << "Destructing " << name << endl; 
    }

  protected:
    string name;
    int  id;
};

class Tutor
{
  public:
    Tutor(Employee& s) : employee(s), id(0){ 
        cout << "Constructing Tutor object" << endl; 
    }
  protected:
    Employee employee;
    int id;
};

void fn(Tutor tutor)
{
    cout << "In function fn()" << endl;
}

int main(int argcs, char* pArgs[])
{
    Employee s("Tom");
    Tutor tutor(s);
    cout << "Calling fn()" << endl;
    fn(tutor);
    cout << "Back in main()" << endl;

    return 0;
}

Result


Related Tutorials