Copy constructor vs copy assignment
suggest changeThe copy constructor and the copy assignment operator can appear in the same class. This code is similar to the two examples above:
#include <iostream>
#include <string>
using std::cout;
using std::endl;
class Foo
{
public:
Foo(int data)
{
this->data = data;
}
~Foo(){};
Foo(const Foo& rhs)
{
data = rhs.data;
}
Foo& operator=(const Foo& rhs)
{
data = rhs.data;
return *this;
}
int data;
};
int main()
{
Foo foo(2); //Foo(int data) / Normal Constructor called
Foo foo2 = foo; //Copy Constructor Called
cout << foo2.data << endl;
Foo foo3(42);
foo3=foo; // Copy assignment operator called
cout << foo3.data << endl;
}
2
2
Foo foo2 = foo; initializes a new object, so the copy constructor runs. foo3 = foo assigns to an object that already exists, so the copy assignment operator runs.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents