For self-defined classes, it may not make sense in some cases to simply copy the contents of the class. The programmer of a class can therefore tell the compiler which code to use for copying. This is done by defining the so-called copy constructor, i.e. a constructor that receives a constant reference of the same class as an argument.
Such a constructor takes an object of its own class as a parameter and initializes itself based on the passed object. A copy constructor is applied to uninitialized objects. It assigns a copy of the source object to an uninitialized target object.
class ClassName {
public:
// create a default constructor
ClassName() {
// Constructor code
}
// create a copy constructor
ClassName(ClassName &obj) {
// Constructor code
}
};
int main() {
// create object using default constructor
ClassName cn1;
// create object using copy constructor
ClassName cn2 = cn1;
return 0;
}
#include <iostream>
using namespace std;
class Cube {
private:
int length, width, height;
public:
Cube(int a, int b, int c) {
length = a;
width = b;
height = c;
}
Cube(Cube &obj) {
length = obj.length;
width = obj.width;
height = obj.height;
}
int getVolume() {
return length * width * height;
}
};
int main() {
Cube c1(2, 4, 6);
Cube c2 = c1;
cout << c1.getVolume() << endl;
cout << c2.getVolume() << endl;
return 0;
}
48
48