Operator overloading in C++

Level 4230 keystrokes

Overloads the + operator for a Vector2 class so that a + b adds the components, then prints 4, 6.

C++ code

1class Vector2 {
2public:
3 int x, y;
// Constructor: the initializer list copies the parameters into the members of the same name
4 Vector2(int x, int y) : x(x), y(y) {}
// Defines what a + b means; the left operand is *this, the right one is v
5 Vector2 operator+(const Vector2& v) {
// Return a new vector with the components added
6 return Vector2(x + v.x, y + v.y);
7 }
8};
9
// Create a = (1, 2) and b = (3, 4)
10Vector2 a(1, 2), b(3, 4);
// Calls a.operator+(b), giving (4, 6)
11Vector2 c = a + b;
// Print 4, 6
12cout << c.x << ", " << c.y << endl;

Output

4, 6
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.

  • ,× 8
  • <× 8
  • (× 7
  • )× 7
  • ;× 6
  • .× 4
  • +× 4
  • {× 3
  • }× 3
  • :× 2

More C++ examples at level 4

← C++ typing practice