...

/

NSDMI: Copy and Move Constructors

NSDMI: Copy and Move Constructors

In this lesson, you will learn how non-static data member initialization works with move and copy constructors.

We'll cover the following...

Copy constructor

The compiler initializes the fields in all the constructors, including the copy and move constructors. However, when a copy or move constructor is the default, there’s no need to perform that extra initialization.

Now, let’s update our previous examples with copy constructors:

Press + to interact
#include <iostream>
#include <string>
int initA() {
std::cout << "initA() called\n";
return 1;
}
std::string initB() {
std::cout << "initB() called\n";
return "World";
}
struct SimpleType {
int a { initA() };
std::string b { initB() };
SimpleType() { }
SimpleType(std::string s) : b(std::move(s)) { }
SimpleType(const SimpleType& other) {
std::cout << "copy ctor\n";
a = other.a;
b = other.b;
};
};
int main() {
SimpleType t1;
std::cout << "SimpleType t2 = t1:\n";
SimpleType t2 = t1;
}

Run the code to see the ...