fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. class Student {
  5. private:
  6. int roll;
  7. string name;
  8. float cgpa;
  9.  
  10. public:
  11. // Default constructor
  12. Student() {
  13. roll = 11130;
  14. name = "Fahim";
  15. cgpa = 3.45;
  16. }
  17.  
  18. // ✅ Copy constructor
  19. Student(Student &obj) {
  20. roll = obj.roll;
  21. name = obj.name;
  22. cgpa = obj.cgpa;
  23. }
  24.  
  25. // Display function
  26. void display() {
  27. cout << "Roll: " << roll << endl;
  28. cout << "Name: " << name << endl;
  29. cout << "CGPA: " << cgpa << endl;
  30. }
  31. };
  32.  
  33. int main() {
  34. Student s1; // default constructor
  35. Student s2 = s1; // ✅ copy constructor called
  36.  
  37. cout << "Student 1:\n";
  38. s1.display();
  39.  
  40. cout << "\nStudent 2 (Copied):\n";
  41. s2.display();
  42.  
  43. return 0;
  44. }
  45.  
Success #stdin #stdout 0.01s 5320KB
stdin
Standard input is empty
stdout
Student 1:
Roll: 11130
Name: Fahim
CGPA: 3.45

Student 2 (Copied):
Roll: 11130
Name: Fahim
CGPA: 3.45