hi everyone
I want to point out that using copy constructors without knowing is very confusing!!
For example, I wrote the following code to try it out:
#include <iostream>
using namespace std;
#include <cstring>
class Foo
{
int x;
public:
Foo() : x(0) { cout << "Foo() constructor called" << endl; } //constructor 1
Foo(const int in) : x(in) { cout << "Foo(in) constructor called" << endl; } //constructor 2
~Foo() { cout << "Foo() destructor called" << endl; } //destructor
void Results()
{
cout << "X: " << x << endl;
}
};
int main(int argc, char* argv[])
{
Foo f1(1); //1 arg constructor called.
f1.Results();
Foo f2(f1); //Copy constructor called.
f2.Results();
Foo f3 = f2; //Same as Foo f3(f2);
f3.Results();
Foo f4(4);
f4.Results();
f3 = f4;
f3.Results();
return 0;
}
As you can see, f2 & f3 contain exactly the same values as f1 object. And then later f3 is a duplicate of f4.
However, if I have the following code (introducing the definition of copy constructor (& operator=) f2 & f3 are no longer copies of f1. How come??
#include <iostream>
using namespace std;
#include <cstring>
class Foo
{
int x;
public:
Foo() : x(0) { cout << "Foo() constructor called" << endl; } //constructor 1
Foo(const int in) : x(in) { cout << "Foo(in) constructor called" << endl; } //constructor 2
Foo(const Foo &f) //Copy constructor
{
cout << "Copy constructor called" << endl;
}
~Foo() { cout << "Foo() destructor called" << endl; } //destructor
void Results()
{
cout << "X: " << x << endl;
}
void operator=(Foo &f)
{
cout << "hello" << endl;
}
};
int main(int argc, char* argv[])
{
Foo f1(1); //1 arg constructor called.
f1.Results();
Foo f2(f1); //Copy constructor called.
f2.Results();
Foo f3 = f2; //Same as Foo f3(f2);
f3.Results();
Foo f4(4);
f4.Results();
f3 = f4; // Operator= called.
f3.Results();
return 0;
}
Worse is the fact that f3 is no longer member-wise copied, but Operator function is called instead!
This is wierd...
Yes! There are kangaroos in Australia but I haven't seen them...yet