Here's an example program to illustrate the use of a copy constructor in C++:
#include <string>
using namespace std;
class Person {
private:
string name;
int age;
public:
Person(string n, int a) {
name = n;
age = a;
}
// Copy constructor
Person(const Person& p) {
name = p.name;
age = p.age;
}
void display() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};
int main() {
// Create a person object
Person p1("John", 30);
// Call the display function
cout << "Original object:" << endl;
p1.display();
// Create a new person object using the copy constructor
Person p2 = p1;
// Call the display function for the new object
cout << "Copied object:" << endl;
p2.display();
return 0;
}
In this example, we have a Person class that has a constructor for initializing the name and age member variables. We also define a copy constructor that takes a reference to another Person object and initializes the current object's member variables with the same values.
In the main() function, we first create a Person object p1 with the name "John" and age 30. We then call the display() function to print the object's details.
Next, we create a new Person object p2 using the copy constructor, passing in p1. This creates a new object with the same name and age values as p1.
Finally, we call the display() function for p2 to print its details. We can see that p2 has the same details as p1, which confirms that the copy constructor worked as expected.
No comments:
Post a Comment
If you have any doubts, please let me know