Copy constructor in C++

Level 4214 keystrokes

Defines a custom copy constructor that copies the value and prints a message; initializing d2 from d1 calls it, so Copy: 42 is printed before 42.

C++ code

1class Data {
// Private member holding the value
2 int val;
3public:
// Ordinary constructor taking an int
4 Data(int v) : val(v) {}
// Copy constructor: builds a new object from an existing one passed as const reference
5 Data(const Data& other) : val(other.val) {
// Announce the copy: prints Copy: 42
6 cout << "Copy: " << val << endl;
7 }
// Getter for the stored value
8 int get() { return val; }
9};
10
// Uses the int constructor (no message)
11Data d1(42);
// Initialization from d1 (not assignment) calls the copy constructor
12Data d2 = d1;
// The copy has the same value: prints 42
13cout << d2.get() << endl;

Output

Copy: 42
42
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • <× 10
  • ;× 7
  • (× 7
  • )× 7
  • :× 4
  • {× 4
  • }× 4
  • .× 2
  • "× 2
  • &× 1

More C++ examples at level 4

← C++ typing practice