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 value2 int val;3public: // Ordinary constructor taking an int4 Data(int v) : val(v) {} // Copy constructor: builds a new object from an existing one passed as const reference5 Data(const Data& other) : val(other.val) { // Announce the copy: prints Copy: 426 cout << "Copy: " << val << endl;7 } // Getter for the stored value8 int get() { return val; }9};10 // Uses the int constructor (no message)11Data d1(42);// Initialization from d1 (not assignment) calls the copy constructor12Data d2 = d1;// The copy has the same value: prints 4213cout << d2.get() << endl;Output
Copy: 42 42
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