Search⌘ K
AI Features

Discussion: Monsters on the Move

Understand the difference between move and copy constructors by analyzing object initialization with std::move in C++. Learn to identify common issues and fix move constructor implementations to write efficient, correct code.

Run the code

Now, it’s time to execute the code and observe the output.

C++ 17
#include <iostream>
struct Monster
{
Monster() = default;
Monster(const Monster &other)
{
std::cout << "Monster copied\n";
}
Monster(Monster &&other)
{
std::cout << "Monster moved\n";
}
};
struct Jormungandr : public Monster
{
Jormungandr() = default;
Jormungandr(const Jormungandr &other) : Monster(other)
{
std::cout << "Jormungandr copied\n";
}
Jormungandr(Jormungandr &&other) : Monster(other)
{
std::cout << "Jormungandr moved\n";
}
};
int main()
{
Jormungandr jormungandr1;
Jormungandr jormungandr2{std::move(jormungandr1)};
}

Understanding the output

When we initialize the second Jormungandr with a moved-from object, the move constructor gets called for Jormungandr but the copy constructor for Monster. Why is that?

As we learned in the ...