Copy Constructor in c++
#include<iostream>
using namespace std;
class student {
public:
string name;
student(string n) {
name = n;
}
student(student &s) {
name = s.name;
}
void display() {
cout << "Name of Student is : " << name << endl;
}
};
int main() {
student s1("Abc");
student s2 = s1;
cout << "--- Before modification ---" << endl;
s1.display();
s2.display();
s2.name = "Xyz";
cout << "\n--- After modification ---" << endl;
s1.display();
s2.display();
return 0;
}
Explanation :
Direct Assignment: Is code mein name = s.name; ho raha hai. Kyunki string aik object hai, C++ iski value ko copy kar deta hai.
Independent Objects: Jab aapne s2.name = "Xyz"; kiya, to sirf s2 ka dabba (variable) update hua. s1 ka dabba "Abc" hi raha.
Output Difference: * Modification se pehle: Dono "Abc" thay.
Modification ke baad: s1 "Abc" raha aur s2 "Xyz" ban gaya.
Output:
--- Before modification ---
Name of Student is : Abc
Name of Student is : Abc
--- After modification ---
Name of Student is : Abc
Name of Student is : Xyz
Post a Comment