how to overloading in c++ code example

Example 1: c++ function overload

/*A function over load in c++ is when you take a function with the same definition but change the input variables.
  This can include multiple functions with the same name see below
  */
#include <iostream>
using namespace std;

int function1(int var1){//example of single variable
	//do somthing
}
int function1(int var1,int var2){//of overload
	//do somthing	
}
int function1(int var1,string var3){//of overload
	//do somthing	
}

int main(){
 
  cout << "Hello World" << endl;
  function1(4);
  function1(3,-90);
  function1(34,"it works");//these should all work even tho they have different input variables
  return 0;
}

Example 2: operator overloading in c++

Box operator+(const Box&);

Example 3: c++ overload operator

#include <iostream>

class ExampleClass {
  public:
    ExampleClass() {}
  	ExampleClass(int ex) {
      example_ = 0;
    }
    int&       example()        { return example_; }
    const int& example() const  { return example_; }
  	//Overload the "+" Operator
  	ExampleClass operator+ (const ExampleClass& second_object_of_class) {
    	ExampleClass object_of_class;
    	object_of_class.example() = this -> example() + second_object_of_class.example();
    	return object_of_class;
  	}
  private:
  	int example_;
};

int main() {
  ExampleClass c1, c2;
  c1.example() = 1;
  c2.example() = 2;
  ExampleClass c3 = c1 + c2;
  //Calls operator+() of c1 with c2 as second_object_of_class
  //c3 gets set to object_of_class
  std::cout << c3.example();
}

Tags:

Cpp Example