Copy constructor
suggest changeA copy constructor initializes a new object from an existing object of the same type. It is not an assignment. Foo foo2 = foo; copy-initializes foo2, so the copy constructor runs even though the punctuation looks like assignment. There is no “assignment constructor”; copying into an existing object is the copy assignment operator.
#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;
}
int data;
};
int main()
{
Foo foo(2); //Foo(int data) called
Foo foo2 = foo; // Copy Constructor called
cout << foo2.data << endl;
}
Foo foo2 = foo; initializes foo2 from foo. The int constructor is not used for foo2, because the copy constructor supplies data from foo. Here is an example output: http://cpp.sh/5iu7
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents