overloaded function 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: c++ overloaded == operator

#include <iostream>
#include <string>
 
class Car
{
private:
    std::string m_make;
    std::string m_model;
 
public:
    Car(const std::string& make, const std::string& model)
        : m_make{ make }, m_model{ model }
    {
    }
 
    friend bool operator== (const Car &c1, const Car &c2);
    friend bool operator!= (const Car &c1, const Car &c2);
};
 
bool operator== (const Car &c1, const Car &c2)
{
    return (c1.m_make== c2.m_make &&
            c1.m_model== c2.m_model);
}
 
bool operator!= (const Car &c1, const Car &c2)
{
    return !(c1== c2);
}
 
int main()
{
    Car corolla{ "Toyota", "Corolla" };
    Car camry{ "Toyota", "Camry" };
 
    if (corolla == camry)
        std::cout << "a Corolla and Camry are the same.\n";
 
    if (corolla != camry)
        std::cout << "a Corolla and Camry are not the same.\n";
 
    return 0;
}

Tags:

Cpp Example