In C ++, the compiler creates a default constructor if we don’t define our own. The default constructor created by the compiler has an empty body, that is, it does not assign default values to data members (in Java, default constructors do).

If we don’t write our own copy constructor, the compiler creates one as well. Unlike the default constructor, the copy constructor created by the compiler does not have an empty body and copies all the data members of the passed object into the object being created.

What happens when we just write the copy constructor – does the compiler create the default constructor?

If we write any constructor, even if it is a copy constructor, the compiler does not create the default constructor. For example, the following program does not compile.

#include <iostream>using namespace std; class Point{int x, y; public:Point(const Point &p) { x = p.x; y = p.y; }}; int main(){Point p1; // COMPILER ERRORPoint p2 = p1; return 0; }Copy the code

Output: Compiler error: No matching function can be called ‘Point :: Point ()

How about the reverse – what happens when we write a normal constructor instead of a copy constructor?

The reverse is not true. If we don’t write our own copy, the compiler creates a copy constructor. Even if we write another constructor in the class, the compiler creates it. For example, the following program works fine.

#include <iostream>using namespace std; class Point{int x, y; public:Point(int i, int j) { x = 10; y = 20; }int getX() { return x; }int getY() { return y; }}; int main(){Point p1(10, 20); Point p2 = p1; // This compiles finecout << "x = " << p2.getX() << " y = " << p2.getY(); return 0; }Copy the code

Output:

x = 10 y = 20

Therefore, we need to write the copy constructor.

And that’s all for today. I hope I can help you

In addition, if you want to improve your programming ability, learn C language C++ programming! Overtake on the curve, one step faster! The author here may be able to help you ~

C language C++ programming learning exchange circle, **QQ group [951258402] ** wechat public number: C language programming learning base

Share (source code, project actual combat video, project notes, basic introduction tutorial)

Welcome to change careers and learn programming partners, use more information to learn and grow faster than their own thinking oh!

Programming learning video sharing: