How to use operator overloading in C++

1 Answer

0 votes
#include <iostream>

class Example {
public: 
    int a;
    int b;

    Example() {} 
  
    Example(int a, int b) { 
        this->a = a;
        this->b = b;
    }
  
    Example operator+(Example obj) {
        Example result; 
        result.a = this->a + obj.a;
        result.b = this->b + obj.b;
        
        return result;
    }
};
  
int main() {
    Example obj1(7, 9);
    Example obj2(2, 4);
    Example sum;
  
    sum = obj1 + obj2;
  
    std::cout << sum.a << " " << sum.b;
}




/*
run:

9 13

*/

 



answered Dec 2, 2022 by avibootz

Related questions

1 answer 238 views
1 answer 261 views
1 answer 228 views
2 answers 286 views
1 answer 265 views
265 views asked Sep 6, 2015 by avibootz
1 answer 238 views
...