Min menu

Pages

VB

Overloading concept in C++


ConcepttheOverloadinginC++

OverloadingIt means defining more than one factor, function or constructor that have the same name but differ in the number or type of parameters.

When defining more than one constructor with the same name, the goal is that when creating an object there is more than one method available to pass primitive values ​​to its properties.
When defining more than one function with the same name, the goal is for them to perform the same operation, taking into account the number and types of values ​​that are passed to the function when it is called.
When defining more than one operator with the same code, the goal is to reduce the code size when dealing with objects.

ConditionstheOverloadinginC++

  • It is applied only to factors, functions and contructors.

  • They must have the same name.

  • They should differ in the type or number of parameters.

  • For functions, the return type is unimportant because the compiler cannot differentiate between functions if they differ only in the return type.


Factors we can do toOverload in C++

+
-
*
/
%
^
&
|
~
!
,
=
<>
<=
>=
++
--
<<
>>
==
!=
&&
||
+=
-=
/=
%=
^=
&=
|=
*=
<<=
>>=
[]
()
->
->*
new
new []
delete
delete []

Factors we can't do toOverload in C++

    . :: ?: sizeof      

Comprehensive examples oftheOverloadinginC++


first example

Definition of functions that have the same name and differ in the type of parameters.

In the following example, we have defined two functions whose name sumand type voidare different from each other in terms of parameters.
The first function is to collect any two numbers of their kind intthat we pass to it when it is called, and then print the result.
The second function is to collect any two numbers of their kind floatthat we pass to it when it is called, and then print the result.

An example of defining functions with the same name but different parameters.

main.cpp
      #include <iostream>
	  
		  using namespace std;
	  
		  // it prints the result of their sum int when it is called we pass it two values ​​of type sum here we have defined a function named
		  void sum(int a, int b)
		  {
		  cout << "First method is called ====> " << a << " + " << b << " = " << (a+b) << endl;
		  }
	  
		  // it prints the result of their double when called, we pass it two values ​​of type sum here we have defined a function named
		  void sum(double a, double b)
		  {
		  cout << "Second method is called ===> " << a << " + " << b << " = " << (a+b) << endl;
		  }
	  
		  // main() Here we have defined the function
		  int main()
		  {
		  sum(4, 6); // int The function that takes 2 parameters of their type will be called here
		  sum(2.3, 5.4); // double Here the function that takes 2 parameters of their type will be called
	  
		  return 0;
		  }
    

We will get the following result when running.

      First method is called ====> 4 + 6 = 10
		  Second method is called ===> 2.3 + 5.4 = 7.7
    

As you have noticed here, every time we called the function sum()we found that the compiler called the sum()appropriate function for the type of parameters we were passing it to.



second example

Definition of functions that have the same name but differ in the number of parameters.

In the following example, we have defined three functions whose name sumand type voidare different from each other by the number of parameters.
The first function is to add any two numbers that we pass to it when it is called, and then print the result.
The second function is to collect any three numbers that we pass to it when called, and then print the result.

An example is the definition of functions with the same name and different number of parameters.

main.cpp
      #include <iostream>
	  
		  using namespace std;
	  
		  // When called, we pass two numbers to it, and it prints the sum of their sum. Here we have defined a function named
		  void sum(float a, float b)
		  {
		  cout << a << " + " << b << " = " << (a + b) << endl;
		  }
	  
		  // When called, we pass three numbers to it, and it prints their sum. Here we have defined a function named
		  void sum(float a, float b, float c)
		  {
		  cout << a << " + " << b << " + " << c << " = " << (a + b + c) << endl;
		  }
	  
		  // main() Here we have defined the function
		  int main()
		  {
		  sum(1, 3); // which takes two values ​​sum() here the function . will be called
		  sum(1, 3, 7); // which takes three values ​​of sum() here the function . will be called
	  
		  return 0;
		  }
    

We will get the following result when running.

      1 + 3 = 4
		  1 + 3 + 7 = 11
    

As you've noticed here, every time we called the function sum()we found that the compiler called the function sum()with the same number of parameters as we were passing it to.



third example

Defining functions that depend on functions that have the same name.

In the following example, we have defined three functions whose name maximum()and type aredouble.
The first function takes 2 parameters which are numbers, and it gives us the largest number between them.
The second function takes 3 parameters which are numbers, and it gives us the largest number between them.
The third function takes 4 parameters which are numbers, and it gives us the largest number among them.

Example of defining functions that depend on functions that have the same name.

main.cpp
      #include <iostream>
	  
		  using namespace std;
	  
		  // This function gives it two numbers and returns the largest number between them
		  double maximum(double a, double b)
		  {
		  if(a>b)
		  return a;
		  else
		  return b;
		  }
	  
		  // This function gives it three numbers and it returns the largest number between them
		  // It depends on the previous function to compare the first two numbers with the third number
		  double maximum(double a, double b, double c)
		  {
		  if(maximum(a,b)>c)
		  return maximum(a,b);
		  else
		  return c;
		  }
	  
		  // This function gives it three numbers and it returns the largest number between them
		  // It depends on the previous two functions to compare the first three numbers with the fourth number
		  double maximum(double a, double b, double c, double d)
		  {
		  if(maximum(a,b,c)>d)
		  return maximum(a,b,c);
		  else
		  return d;
		  }
	  
		  // main() Here we have defined the function
		  int main()
		  {
	  
		  cout << "The maximum number is: " << maximum(5, 20) << endl; // Here the function with 2 parameters will be called
		  cout << "The maximum number is: " << maximum(5, 20, 15) << endl; // Here the function that takes 3 parameters will be called
		  cout << "The maximum number is: " << maximum(5, 20, 15, 30); // Here the function that takes 4 parameters will be called
	  
		  return 0;
		  }
    

We will get the following result when running.

      The maximum number is: 20
		  The maximum number is: 20
		  The maximum number is: 30
    

As you've noticed here, every time we called the function maximum()we found that the compiler called the function maximum()that had the same number of parameters we were passing to it, and internally we bound the functions together.



Fourth example

Definition of more than one constructor in class.

In the following example, we have defined a class whose name Countryrepresents the information that can be included in any country, and it contains four constructors.
The first constructor does not take any parameters.
The second constructor takes one parameter which is the name of the country.
The third contructor takes two parameters, the name and the area of ​​the country.
The fourth contructor takes three parameters which are the name, area and population of the country.

After creating this class we created four objects from it and each time we used a different constructor to create the object.

Example definition of more than one constructor in class.

main.cpp
      #include <iostream>
	  
		  using namespace std;
	  
		  // which represents the things owned by any country Country Here we have defined the class
		  class Country
		  {
		  public:
		  // it will have these properties, that is, every country will have these properties Country every object of the class
		  string name;
		  double area;
		  long population;
	  
		  // The first constructor does not take parameters
		  Country()
		  {
		  name = "";
		  area = 0;
		  population = 0;
		  }
	  
		  // The second constructor allows you to specify the name of the country directly when creating the object
		  Country(string n)
		  {
		  name = n;
		  area = 0;
		  population = 0;
		  }
	  
		  // The third constructor allows you to specify the country name and area directly when creating the object
		  Country(string n, double a)
		  {
		  name = n;
		  area = a;
		  population = 0;
		  }
	  
		  // The fourth constructor allows you to specify the country name, area and population directly when creating the object
		  Country(string n, double a, long p)
		  {
		  name = n;
		  area = a;
		  population = p;
		  }
	  
		  // This function displays all the information entered into the object
		  void printInfo()
		  {
		  cout << "name: " << name << endl;
		  cout << "area: " << area << endl;
		  cout << "population: " << population << endl;
		  cout << "-------------------" << endl;
		  }
		  };
	  
	  
		  // main() Here we have defined the function
		  int main()
		  {
		  // here each object represents a country, here we have created 4 objects from class
		  Country c1; // c1 Here the first Consecore will be called, i.e. no information about the country the object represents will be passed
		  Country c2("KSA"); // c2 Here the second console will be called, i.e. the name of the country the object represents will be specified
		  Country c3("Turkey", 780580); // c3 Here, the third console will be called, ie the name and area of ​​the country the object represents
		  Country c4("Lebanon", 10452, 4467000); // c4 Here the Quarter Core will be called, ie the name, area and population of the country the object represents
	  
		  // To display the properties of all objects printInfo() here we called the function
		  c1.printInfo();
		  c2.printInfo();
		  c3.printInfo();
		  c4.printInfo();
	  
		  return 0;
		  }
    

We will get the following result when running.

      name:
		  area: 0
		  population: 0
		  --------------------
		  name: KSA
		  area: 0
		  population: 0
		  --------------------
		  name: Turkey
		  area: 780580
		  population: 0
		  --------------------
		  name: Lebanon
		  area: 10452
		  population: 4467000
		  --------------------
    

As you noticed here, the class Countryhas four named constructors Country(), and each constructor allows you to pass certain values ​​directly when creating an object from the class.Country.
Every time we called up the constructor Country(), the translator called up the constructor Country()that had the same number of parameters we were passing it on.



Fifth example

how can you doOverloadfor the operator ++to make it increment the values ​​of the object from which it is called.

In the following example, we have defined a class whose name Playercontains three variables that represent the general information that the player can possess such as his rank gradein the game, his speed speed, and the amount of money moneyhe has collected, in addition to a function named printInfothat displays the values ​​of these variables in an orderly manner.

Here we assumed that any new player will have equal rank 1and speed equal 1and he does not have any money.
When the player is upgraded, his rank and speed will be increased by an amount 1and he will be given an amount 1000as well.

To show you how you can doOverloadFor a factor, we have assigned the factor ++to be used whenever we want to upgrade the player.

In the end, we create an object of the class Player(that is, as if we created a player) and then try to upgrade it by the operator++.

Example

main.cpp
      #include <iostream>
	  
		  using namespace std;
	  
		  // which represents the player here we have defined the class
		  class Player {
	  
		  public:
		  // Here we define the properties of the class
		  int grade;
		  int speed;
		  int money;
	  
		  // Here we define a class constructor in order to give initial values ​​to the properties of the object being created from the class
		  Player()
		  {
		  grade = 1;
		  speed = 1;
		  money = 0;
		  }
	  
		  // Here we have defined a function that prints the object's property values ​​in order when it is called
		  void printInfo()
		  {
		  cout << "Grade = " << grade << endl;
		  cout << "Speed ​​= " << speed << endl;
		  cout << "Money = " << money << endl;
		  cout << "----------------\n";
		  }
	  
		  // Here we have defined what will happen when the ++ is called from any object we create from the class
		  void operator++ (int)
		  {
		  // It will add 1000 money, 1 will be added, the speed will be 1 and the grade will be
		  grade += 1;
		  speed += 1;
		  money += 1000;
		  }
		  };
	  
		  // main() Here we have defined the function
		  int main()
		  {
		  // Any new player, here we have created an object from the class
		  player player;
	  
		  // player to display the default values ​​owned by the printInfo() object here we called the function
		  player.printInfo();
	  
		  // until player is upgraded here we called ++ from object
		  player++;
	  
		  // player again to display the values ​​that the printInfo() object now has, here we called the function
		  player.printInfo();
	  
		  return 0;
		  }
    

We will get the following result when running.

      Grade = 1
		  Speed ​​= 1
		  Money = 0
		  ----------------
		  Grade = 2
		  Speed ​​= 2
		  Money = 1000
		  ----------------
    


Sixth example

how can you doOverloadThe operator +has to have it add the values ​​of one object over the values ​​of another object.

In the following example, we will apply one of the rules of mathematics that we use to measure the distance between two points.
In principle, each point will have a horizontal value denoted by a letter x, and a vertical value denoted by a lettery.

Now, since we will need two points and each point has it x, yit is logical to create a class named after Pointit and put two variables named it xandy.
Then whenever we want to create a point, we create an object from the class Pointand give it values.

The class Pointwe put in a constructor to pass values ​​directly to the object from which it is created, as we didOverloadfor the factor +so that we can use it to get the distance between any two points (two objects) by putting it between them.

Example

main.cpp
      #include <iostream>
		  #include <cmath>
	  
		  using namespace std;
	  
		  // which represents the point here we have defined the class
		  class Point {
	  
		  public:
		  // Here we define the properties of the class
		  int x;
		  int y;
	  
		  // Here we define a class constructor in order to give initial values ​​to the properties of the object being created from the class
		  Point(int x, int y)
		  {
		  this->x = x;
		  this->y = y;
		  }
	  
		  // and get the distance between them Point on an object from the class Point of the symbol + so we can add an object from the overload class here we did
		  double operator+ (Point point)
		  {
		  return sqrt(pow(point.x - this->x, 2) + pow(point.y - this->y, 2));
		  }
		  };
	  
		  // main() Here we have defined the function
		  int main()
		  {
		  // any two points, here we have created two class objects
		  Point p1(1, 5);
		  Point p2(4, 8);
	  
		  // distance and then we store the result in the variable p2 and the point p1 here we use the + operator to get the distance between the point
		  double distance = p1 + p2;
	  
		  // distance Here we have shown the distance between the two points which we have stored in the variable
		  cout << "Distance between p1 and p2 = " << distance;
	  
		  return 0;
		  }
    

We will get the following result when running.

      Distance between p1 and p2 = 4.24264