Implementation of the C++ copy constructor
- 2020-06-12 10:07:27
- OfStack
A copy constructor is a special constructor that has the properties of a 1-like constructor. Its function is to initialize a class object to be created with a known object. The parameter passing mode of the copy constructor must be passed by reference. See example:
#include <iostream>
#include <cstring>
using namespace std ;
class Student
{
private :
char name[8];
int age ;
char sex ;
int score ;
public :
void disp(); // A function declaration that prints the information
Student(char name[],int age , char sex ,int score); // Constructor declaration
Student(Student &dx); // Copy the constructor declaration
~Student(); // The declaration of the destructor
};
// Implementation of the print information function
void Student::disp()
{
cout << this->name << endl ;
cout << this->age << endl ;
cout << this->sex << endl ;
cout << this->score << endl ;
}
// Implementation of the constructor
Student::Student(char name[],int age , char sex ,int score)
{
strcpy(this->name,name);
this->age = age ;
this->sex = sex ;
this->score = score ;
}
// Implementation of the copy constructor
Student::Student(Student &dx)
{
strcpy(this->name , dx.name);
this->age = dx.age ;
this->sex = dx.sex ;
this->score = dx.score ;
}
// Implementation of the destructor
Student::~Student()
{
cout << " End of the program " << endl ;
}
int main(void)
{
Student stu1("YYX",23,'N',86);
Student stu2(stu1);
stu1.disp() ;
stu2.disp() ;
return 0 ;
}
Operation results:
[
YYX
23
N
86
YYX
23
N
86
End of the program
End of the program
conclusion