Skip to content

Instantly share code, notes, and snippets.

@rastr-0
Created November 6, 2025 17:58
Show Gist options
  • Select an option

  • Save rastr-0/c19a86a54f56160422081e711ca9fa14 to your computer and use it in GitHub Desktop.

Select an option

Save rastr-0/c19a86a54f56160422081e711ca9fa14 to your computer and use it in GitHub Desktop.
An example of the c++ class with overloaded operators
#include <iostream>
#include <utility>
#include <cmath>
using namespace std;
class Point {
private:
float x;
float y;
public:
Point(float, float);
Point(std::pair<float, float>);
Point() {};
~Point() {};
void set_points(float, float);
std::pair<float, float> get_points() const;
float length() const;
Point operator *(const Point& other) const {
auto other_data = other.get_points();
return Point(this->x * other_data.first, this->y * other_data.second);
}
Point operator +(const Point& other) const {
auto other_data = other.get_points();
return Point(this-> x + other_data.first, this->y + other_data.second);
}
Point& operator =(const Point& other){
if (this != &other) {
this->x = other.x;
this->y = other.y;
}
return *this;
}
bool operator <(const Point& other) const {
return this->length() < other.length();
}
bool operator >(const Point& other) const {
return this->length() > other.length();
}
};
Point::Point(float x, float y) {
this->x = x;
this->y = y;
}
Point::Point(std::pair<float, float> another) {
this->x = another.first;
this->y = another.second;
}
float Point::length() const {
return sqrt(pow(this->x, 2) + pow(this->y, 2));
}
void Point::set_points(float x, float y) {
this->x = x;
this->y = y;
}
pair<float, float> Point::get_points() const {
return make_pair(this->x, this->y);
}
int main() {
Point *a = new Point(10.1, 9.8); // Point <-- class; a <-- object
auto data_a = a->get_points();
cout << "Point a: " << data_a.first << " | " << data_a.second << endl;
Point *b = new Point();
b->set_points(9.9, 0.2);
auto data_b = b->get_points();
cout << "Point b: " << data_b.first << " | " << data_b.second << endl;
Point *c = new Point();
*c = *a + *b;
auto data_c = c->get_points();
cout << "Point c = a + b: " << data_c.first << " | " << data_c.second << endl;
Point *d = new Point();
*d = (*c) * (*a);
auto data_d = d->get_points();
cout << "Point d = c * a: " << data_d.first << " | " << data_d.second << endl;
cout << "Check if a > b: " << (bool(*a > *b) ? "yes" : "no") << endl;
cout << "Check if c < d: " << (bool(*c < *d) ? "yes" : "no") << endl;
// free memory
delete(a);
delete(b);
delete(c);
delete(d);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment