Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

c++ operator overloading

#include <iostream>

class foo{
public: 
  foo(){} //Empty constructor
  
  foo(int a, int b){ //Constructor takes 2 args to set the value of a and b.
    this->a = a;
    this->b = b;
  }
  
  int a;
  int b;
  
  /*
  A function that returns a foo class when a "+" operator is applied to
  2 objects of type foo.
  */
  foo operator+(foo secondValue){
    foo returnValue; //Temporary class to return.
    returnValue.a = this->a + secondValue.a;
    returnValue.b = this->b + secondValue.b;
    return returnValue;
};
  
int main(){
  foo firstValue(1,3);
  foo secondValue(1,5);
  foo sum;
  
  sum = firstValue + secondValue;
  std::cout << sum.a << " " << sum.b << "
";
  
  return 0;
}
 
PREVIOUS NEXT
Tagged: #operator #overloading
ADD COMMENT
Topic
Name
8+2 =