Copy Constructor tạo đối tượng mới và khởi tạo từ đối tượng cùng lớp. Nếu không định nghĩa, trình biên dịch tự tạo. Bắt buộc cho lớp có con trỏ hoặc cấp phát bộ nhớ động.
Ví dụ
#include <iostream>
using namespace std;
class Demo {
private:
int num1, num2;
public:
Demo(int n1, int n2) {
num1 = n1;
num2 = n2;
}
Demo(const Demo &n) {
num1 = n.num1;
num2 = n.num2;
}
void display() {
cout << "num1 = " << num1 << endl;
cout << "num2 = " << num2 << endl;
}
};
int main() {
Demo obj1(10, 20);
Demo obj2 = obj1;
obj1.display();
obj2.display();
return 0;
}
Kết quả
num1 = 10 num2 = 20 num1 = 10 num2 = 20
Lớp Demo với Constructor và Copy Constructor
class Demo {
private:
int num1, num2;
public:
Demo(int n1, int n2) {
num1 = n1;
num2 = n2;
}
Demo(const Demo &n) {
num1 = n.num1;
num2 = n.num2;
}
void display() {
cout << "num1 = " << num1 << endl;
cout << "num2 = " << num2 << endl;
}
};
Hàm main()
Demo obj1(10, 20);
Demo obj2 = obj1;
obj1.display();
obj2.display();
obj1 khởi tạo bằng parameterized constructor. obj2 khởi tạo bằng copy constructor sao chép từ obj1.