Example of copy constructor
Example:1
Write a C++ program to declare a class named student with attributes as roll, name, and per, further take input for details and display them?
Sol:
#include <iostream> #include<string.h> using namespace std; class student { private: int roll; char name[20]; float per; public: student(); //default constructor student(int r,char *n,float p); //Parameterized constructor student(student &s); //copy constructor void read(); void show(); }; //default constructor student::student() { roll=0; name[0]='\0'; per=0; } //Parameterized constructor student::student(int r,char *n,float p) { roll=r; strcpy(name,n);//strcpy() : header file : string.h per=p; } //copy constructor student::student(student &s) { roll=s.roll; strcpy(name,s.name); per=s.per; } void student::read() { cout<<"Enter roll,name and per "; cin>>roll>>name>>per; } void student::show() { cout<<"roll "<<roll<<" name "<<name<<" per "<<per<<endl; } int main() { student s1,s2(1001,"Kapil",94); s1.show(); s2.show(); student s3(s2); s3.show(); return 0; }
/* Output */ roll 0 name per 0 roll 1001 name Kapil per 94 roll 1001 name Kapil per 94
Example:2
Write a C++ program to declare a class named employee with attributes as empno, name and salary, further take input for details and display them?
Sol:
#include <iostream> #include<string.h> using namespace std; class employee { private: int empno; char name[20]; float sal; public: employee(); //default constructor employee(int a,char *n,float s); //Parameterized constructor employee(employee &e); //copy constructor void read(); void show(); }; //default constructor employee::employee() { empno=0; name[0]='\0'; sal=0; } //Parameterized constructor employee::employee(int a,char *n,float b) { empno=a; strcpy(name,n);//strcpy() : header file : string.h sal=b; } //copy constructor employee::employee(employee &e) { empno=e.empno; strcpy(name,e.name); sal=e.sal; } void employee::read() { cout<<"Enter empno,name and sal "; cin>>empno>>name>>sal; } void employee::show() { cout<<"empno "<<empno<<" name "<<name<<" sal "<<sal<<endl; } int main() { employee e1,e2(1001,"Kapil",45000); e1.show(); e2.show(); employee e3(e2); e3.show(); return 0; }
/* Output */ empno 0 name sal 0 empno 1001 name Kapil sal 45000 empno 1001 name Kapil sal 45000