ตัวสร้างการคัดลอกคือตัวสร้างที่สร้างวัตถุโดยเริ่มต้นวัตถุด้วยวัตถุระดับเดียวกันซึ่งสร้างไว้ก่อนหน้านี้ ตัวสร้างการคัดลอกใช้เพื่อ -
- เริ่มต้นวัตถุหนึ่งจากวัตถุประเภทเดียวกันอีกชนิดหนึ่ง
- คัดลอกวัตถุเพื่อส่งผ่านเป็นอาร์กิวเมนต์ไปยังฟังก์ชัน
- คัดลอกวัตถุเพื่อส่งคืนจากฟังก์ชัน
หากคอนสตรัคเตอร์การคัดลอกไม่ได้กำหนดไว้ในคลาส คอมไพเลอร์จะกำหนดหนึ่งตัว หากคลาสมีตัวแปรพอยน์เตอร์และมีการจัดสรรหน่วยความจำแบบไดนามิก จำเป็นต้องมีตัวสร้างการคัดลอก รูปแบบที่พบบ่อยที่สุดของตัวสร้างการคัดลอกแสดงไว้ที่นี่ -
classname (const classname &obj) {
// body of constructor
} ที่นี่ obj เป็นการอ้างอิงถึงวัตถุที่กำลังใช้ในการเริ่มต้นวัตถุอื่น
โค้ดตัวอย่าง
#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;
};
// Member functions definitions including constructor
Line::Line(int len) {
cout << "Normal constructor allocating ptr" << endl;
// allocate memory for the pointer;
ptr = new int;
*ptr = len;
}
Line::Line(const Line &obj) {
cout << "Copy constructor allocating ptr." << endl;
ptr = new int;
*ptr = *obj.ptr; // copy the 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;
}
// Main function for the program
int main() {
Line line(10);
display(line);
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 ); // simple constructor
Line( const Line &obj); // copy constructor
~Line(); // destructor
private:
int *ptr;
};
// Member functions definitions including constructor
Line::Line(int len) {
cout << "Normal constructor allocating ptr" << endl;
// allocate memory for the pointer;
ptr = new int;
*ptr = len;
}
Line::Line(const Line &obj) {
cout << "Copy constructor allocating ptr." << endl;
ptr = new int;
*ptr = *obj.ptr; // copy the 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;
}
// Main function for the program
int main() {
Line line1(10);
Line line2 = line1; // This also calls copy constructor
display(line1);
display(line2);
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!