example4_copy_constructor.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <string>

class Student {
private:
    std::string name;
    int* score;

public:
    // Regular constructor
    Student(const std::string& n, int s) : name(n), score(new int(s)) {
        std::cout << "Regular constructor called" << std::endl;
    }

    // Copy constructor
    Student(const Student& other) : name(other.name), score(new int(*other.score)) {
        std::cout << "Copy constructor called" << std::endl;
    }

    // Destructor
    ~Student() {
        delete score;
    }

    void display() const {
        std::cout << "Name: " << name << ", Score: " << *score << std::endl;
    }

    void setScore(int s) {
        *score = s;
    }
};

int main() {
    Student student1("Bob", 85);
    Student student2 = student1;  // Copy constructor called

    std::cout << "Student 1: ";
    student1.display();
    std::cout << "Student 2: ";
    student2.display();

    student2.setScore(90);

    std::cout << "After changing student2's score:" << std::endl;
    std::cout << "Student 1: ";
    student1.display();
    std::cout << "Student 2: ";
    student2.display();

    return 0;
}
Back to constructor