Operator Overloading in C++

Level 5267 keystrokes

Overloads operator+ for Vector2D so two vectors can be added with a + b. The result (4, 6) is printed.

C++ code

// Class for a 2D vector
1class Vector2D {
2public:
// Public x and y components
3 double x, y;
// In the initializer list, x(x) sets the member x from the parameter x
4 Vector2D(double x, double y) : x(x), y(y) {}
5
// Overloads +: takes the other vector by const reference and does not modify *this
6 Vector2D operator+(const Vector2D& v) const {
// Returns a new vector with the components added
7 return Vector2D(x + v.x, y + v.y);
8 }
9};
10
// Two vectors: (1, 2) and (3, 4)
11Vector2D a(1, 2), b(3, 4);
// a + b calls a.operator+(b)
12Vector2D c = a + b;
// Prints (4, 6)
13cout << "(" << 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.

  • <× 12
  • ,× 8
  • (× 8
  • )× 8
  • ;× 6
  • "× 6
  • .× 4
  • +× 4
  • {× 3
  • }× 3

More C++ examples at level 5

← C++ typing practice