C++ examples for Class:Constructor
Using the copy constructor
#include <string> #include <cstdio> #include <cstdlib> #include <iostream> using namespace std; class Employee {/* w w w .j a v a 2 s . c o m*/ public: Employee(const char *pName = "no name", int ssId = 0) : name(pName), id(ssId) { cout << "Constructed " << name << endl; } Employee(const Employee& s) : name("Copy of " + s.name), id(s.id) { cout << "Constructed " << name << endl; } ~Employee() { cout << "Destructing " << name << endl; } protected: string name; int id; }; void fn(Employee copy) { cout << "In function fn()" << endl; } int main(int nNumberofArgs, char* pszArgs[]) { Employee s1("Tom", 1234); cout << "Calling fn()" << endl; fn(s1); cout << "Back in main()" << endl; return 0; }