CSC166 Object Oriented Programming

Object Oriented ProgrammingTU Board 2082

Explain copy constructor with an example.

5

Answer

A copy constructor is a constructor that creates a new object as a copy of an existing object of the same class. Its parameter is a reference to an object of the same class:

ClassName(const ClassName &obj);

The parameter must be a reference: passing by value would itself need a copy, causing infinite recursion.

A copy constructor is called when:

  • an object is initialised from another object: Student s2 = s1; or Student s2(s1);
  • an object is passed to a function by value,
  • a function returns an object by value.

If you do not write one, the compiler provides a default copy constructor that copies member by member (a shallow copy).

#include <iostream>
using namespace std;

class Student {
    int roll;
    float marks;
public:
    Student(int r, float m) { roll = r; marks = m; }

    Student(const Student &s) {          // copy constructor
        roll = s.roll;
        marks = s.marks;
        cout << "Copy constructor called\n";
    }

    void show() { cout << "Roll: " << roll << ", Marks: " << marks << endl; }
};

int main() {
    Student s1(7, 82.5);
    Student s2 = s1;       // copy constructor is called here
    s1.show();
    s2.show();
    return 0;
}

Output

Copy constructor called
Roll: 7, Marks: 82.5
Roll: 7, Marks: 82.5

A user-defined copy constructor is essential when the class holds a pointer to dynamic memory. It then allocates new memory and copies the data (a deep copy), so the two objects do not share and later double-free the same memory.

Discussion

Loading…

More Object Oriented Programming questions

All Object Oriented Programming old questions