The copy-constructor is a special method that can be called without really typing its name.
The copy-constructor is called whenever an object is initialized based on another existing object.
Assuming you have:
1 2 3 4 5 6
|
class TestOverload{
public:
int i;
TestOverload(int a = 0);
TestOverload(const TestOverload &T);
};
|
And you write this line:
TestOverload t1 = t2;
t1 is created based on
t2 values. TestOverload(t2) will be called.
Also, if you have:
1 2 3 4
|
void myFunc(TestOverload t)
{
//code
}
|
t will be created based on the object you pass when you call myFunc. This means copy-constructing!
Attention:
t1 = t2;
This doesn't call the copy-constructor.
t1 is already created in this case, it's already constructed. This line calls the assignment operator function.
--
But if you don't want anyone to make these implicit calls, just put the
explicit keyword before the copy constructor. This way, the only way to call the copy-constructor is typing its name. No implicit calls will be made. This also means it won't be possible to pass the object by value to any function, or make initializations like
ClassType obj1 = obj2;
There are other special functions that can be implicitly called, like the converting constructor. This one is more common to make explicit.