Pgm Description: Write a C++ program using a copy constructor to copy the data of one object to another object.
Pgm Details: The program demonstrates how a copy constructor is used to initialize an object with the data from an existing object of the same class.
Pgm Logic:
Define a class code with an integer data member id.
Provide a default constructor to allow object declaration without initialization.
Provide a parameterized constructor to initialize id with a specific value.
Define a copy constructor code(code & x) that copies the id from the source object x.
In the main() function, create an object A with an initial value.
Create objects B and C using different syntax to trigger the copy constructor.
Verify the copies by displaying the id of all objects.
Program Code:
// C++ program to copy data of an object to another object using copy constructor
#include<iostream.h>
#include<conio.h>
class code {
int id;
public:
code() {} // Default constructor
code(int a) { id = a; } // Parameterized constructor
code(code & x) { id = x.id; } // Copy constructor
void display(void) { cout << id; }
};
int main() {
code A(100);
code B(A); // Copy constructor called
code C = A; // Copy constructor called
code D;
D = A; // Assignment operator called (not copy constructor)
cout << "\n id of A: "; A.display();
cout << "\n id of B: "; B.display();
cout << "\n id of C: "; C.display();
cout << "\n id of D: "; D.display();
return 0;
}
Output: id of A: 100 id of B: 100 id of C: 100 id of D: 100
RESULT: Thus the program using copy constructor has been executed and the output was verified.
Remarks: While code C = A looks like an assignment, it is actually an initialization that invokes the copy constructor. The line D = A is a true assignment because D was already initialized.
Program Explanation: The copy constructor takes a reference to an object of the same class as an argument. It allows the programmer to define exactly how an object should be duplicated, ensuring that member variables are copied correctly to the new instance.
eBook ‘C++ Lab Programs Collection’ purchase Link: Google Play Store || Google Books
...till the next post, bye-bye & take care