Copy Constructor เป็น Constructor ที่สร้างอ็อบเจกต์โดยเริ่มต้นด้วยอ็อบเจกต์อีกตัวของคลาสเดียวกันที่สร้างไว้ก่อนหน้านี้ ใช้เพื่อ:
- เริ่มต้นอ็อบเจกต์หนึ่งจากอีกอ็อบเจกต์ชนิดเดียวกัน
- คัดลอกอ็อบเจกต์เพื่อส่งเป็นอาร์กิวเมนต์ให้ฟังก์ชัน
- คัดลอกอ็อบเจกต์เพื่อคืนค่าจากฟังก์ชัน
ถ้าไม่กำหนด Copy Constructor คอมไพเลอร์จะสร้างให้เอง แต่ถ้าคลาสมี Pointer และจัดสรรหน่วยความจำแบบไดนามิก ต้องเขียน Copy Constructor เอง รูปแบบทั่วไป:
classname (const classname &obj) { /* body */ }โดย obj คือ Reference ไปยังอ็อบเจกต์ที่ใช้เริ่มต้นอ็อบเจกต์ใหม่
โค้ดตัวอย่าง
#include <iostream>
using namespace std;
class Line {
public:
int getLength(void);
Line(int len); // simple constructor
Line(const Line &obj); // copy constructor
~Line(); // destructor
private:
int *ptr;
};
Line::Line(int len) {
cout << "Normal constructor allocating ptr" << endl;
ptr = new int; *ptr = len;
}
Line::Line(const Line &obj) {
cout << "Copy constructor allocating ptr." << endl;
ptr = new int; *ptr = *obj.ptr; // copy value
}
Line::~Line(void) {
cout << "Freeing memory!" << endl;
delete ptr;
}
int Line::getLength(void) { return *ptr; }
void display(Line obj) {
cout << "Length of line : " << obj.getLength() << endl;
}
int main() {
Line line(10);
display(line); // pass by value -> calls copy constructor
return 0;
}ผลลัพธ์
Normal constructor allocating ptr Copy constructor allocating ptr. Length of line : 10 Freeing memory! Freeing memory!
ตัวอย่างเพิ่มเติม: สร้างอ็อบเจกต์ใหม่จากอ็อบเจกต์เดิม
โค้ดตัวอย่าง
#include <iostream>
using namespace std;
class Line {
public:
int getLength(void);
Line(int len);
Line(const Line &obj);
~Line();
private:
int *ptr;
};
Line::Line(int len) {
cout << "Normal constructor allocating ptr" << endl;
ptr = new int; *ptr = len;
}
Line::Line(const Line &obj) {
cout << "Copy constructor allocating ptr." << endl;
ptr = new int; *ptr = *obj.ptr;
}
Line::~Line(void) {
cout << "Freeing memory!" << endl;
delete ptr;
}
int Line::getLength(void) { return *ptr; }
void display(Line obj) {
cout << "Length of line : " << obj.getLength() << endl;
}
int main() {
Line line1(10);
Line line2 = line1; // copy constructor called
display(line1); // copy constructor called
display(line2); // copy constructor called
return 0;
}ผลลัพธ์
Normal constructor allocating ptr Copy constructor allocating ptr. Copy constructor allocating ptr. Length of line : 10 Freeing memory! Copy constructor allocating ptr. Length of line : 10 Freeing memory! Freeing memory! Freeing memory!