Avi said:
Whenever a object needs to be copied, copy constructor is called. There
are three situations where copy constructor is called.....
(1) Explicitly:
Suppose there is a class ABC, then in the following cases at 2nd
line of code, copy constructor is called.
ABC a1;
ABC a2 = a1; ...... 2nd line
(2) When a object is passed by value to called function.
(3) When a object is returned by value from called function.
Thanks,
(1)
ABC a2 = a1;
may seem to require operator=( const ABC& ), but it does not. It uses
copy-ctor.
(2)
void fun( ABC a ) // copy-ctor is used
{
}
void main()
{
ABC x;
fun( x );
}
(3)
ABC fun() // copy-ctor is used
{
ABC a;
return a;
}
void main()
{
ABC x = fun();
}
If you do not supply copy-ctor, compiler will generate one. This will copy
each byte in source to destionation, so it will cause problems. Because of
this, I always write following line in my class, even I do not implement it.
It avoids compiler generated copy-ctor and you will get compiler error if
you try to use copy-ctor.
private:
ABC( const ABC& source );
ABC& operator=( const ABC& source );
Compiler will generate assignment operator too, if you do not supply one! In
the case above, I have supplied it, but with missing implementation.
(2)
You can avoid copy-ctor, if fou declare it in this way. It's faster too.
void fun( const ABC& a )
{
}
const says to the caller that fun does not modify the object.
HTH,
JMu