Copy constructor
Integer I1(I2); // copy constructor called
I1 = I2; // Values assigned member by member
why we have to use copy constructor? Instead of using second one.
Sometimes the copy constructor is automatically used.
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 53 54 55
|
#include <iostream>
class Whine {
public:
int i;
Whine()
{
std::clog << this << " : Regular constructor\n";
}
Whine(const Whine &w)
{
std::clog << this << " : Copy constructor from " << &w << '\n';
}
Whine & operator = (const Whine &w)
{
std::clog << this << " : Copy assignment from " << &w << '\n';
return *this;
}
~Whine()
{
std::clog << this << " : Destructor\n";
}
// C++11 only:
/*
Whine(Whine &&w)
{
std::clog << this << " : Move constructor from " << &w << '\n';
}
Whine & operator = (Whine &&w)
{
std::clog << this << " : Move assignment from " << &w << '\n';
return *this;
}
*/
};
void function(Whine w)
{
w.i = 0;
}
int main()
{
Whine w;
function(w);
}
|
0x22ff38 : Regular constructor
0x22ff3c : Copy constructor from 0x22ff38
0x22ff3c : Destructor
0x22ff38 : Destructor |
Last edited on
Topic archived. No new replies allowed.