Back to track
#121 Medium Object-Oriented C++

Operator Overload Unary

Open the editor

Problem

Overload unary - to negate a vector.

Input

No input.

Output

Exactly what the described program prints.

Hints

  1. 1

    Return Vec2(-x, -y)

  2. 2

    Mark const

Worked solution

Reference solution

One correct implementation. Alternative approaches that satisfy the constraints are equally valid — the reviewer judges behaviour, not style.

#include <iostream>
using namespace std;

class Vec2 {
public:
  int x, y;
  Vec2(int x, int y) : x(x), y(y) {}

  Vec2 operator-() const {
    return Vec2(-x, -y);
  }
};

int main() {
  Vec2 v(2, -3);
  Vec2 n = -v;
  cout << n.x << "," << n.y << '\n';
  return 0;
}

© 2026 ChitChat