Get the App
SLTechnology News&Howtos  ›  Development  › 

What is the copy constructor in C++

Shulou Source: shulou.com Published: 2022-06-03 10:55:24 10月30日 Update

This article introduces how the copy constructor function in C++ is, the content is very detailed, interested friends can refer to it, I hope it can help you.

Copy of common variables

Sometimes we define one variable and initialize it with another.

int a_variable=12;int new_variable(a_variable);

It's useful to initialize yourself with an existing variable of the same type.

Is it possible to copy custom types of objects easily through an existing object?

copy constructor

Copy constructor is also called copy constructor, it has only one parameter (since you need to copy, one is enough, if you pass two identical objects there is no meaning, if you pass two different objects, there is no need to call copy constructor), the parameter type is a reference to this class.

If the programmer does not write a copy constructor, the compiler automatically generates a copy constructor that copies byte by byte according to the member variables in the copy constructor (beginners can understand this, in fact, individual compilers do not always automatically generate copy constructors, they may directly copy the values of the source object to the corresponding member variables of the target object, which will be described later).

class MyDate{ int day_; int year_;public: MyDate(int day, int year) { day_ = day; year_ = year; } MyDate(const MyDate& date) { day_ = date.day_; year_ = date.year_; cout

Tags: Function object pointer variable member type compiler build compile parameter point two space memory content case copy character clocked only Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn Docker NVidia Shulou Information Xiaomi