This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Monday, February 27, 2023

Write a program to illustrate copy constructor.

 Here's an example program to illustrate the use of a copy constructor in C++:

#include <iostream>
#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

Slider Widget