C++ Overloading
C++ Overloading (Operator and Function)
C++ allows you to specify more than one definition for a function name or an operator in the same scope, which is called function overloading and operator overloadingrespectively.
An overloaded declaration is a declaration that is declared with the same name as a previously declared declaration in the same scope, except that both declarations have different arguments and obviously different definition (implementation).
When you call an overloaded function or operator, the compiler determines the most appropriate definition to use, by comparing the argument types you have used to call the function or operator with the parameter types specified in the definitions. The process of selecting the most appropriate overloaded function or operator is called overload resolution.
Function Overloading in C++
You can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list. You cannot overload function declarations that differ only by return type.
Following is the example where same function print() is being used to print different data types −
#include <iostream> using namespace std; class printData { public: void print(int i) { cout << "Printing int: " << i << endl; } void print(double f) { cout << "Printing float: " << f << endl; } void print(char* c) { cout << "Printing character: " << c << endl; } }; int main(void) { printData pd; // Call print to print integer pd.print(5); // Call print to print float pd.print(500.263); // Call print to print character pd.print("Hello C++"); return 0; }
When the above code is compiled and executed, it produces the following result −
Printing int: 5 Printing float: 500.263 Printing character: Hello C++
Operators Overloading in C++
You can redefine or overload most of the built-in operators available in C++. Thus, a programmer can use operators with user-defined types as well.
Overloaded operators are functions with special names: the keyword "operator" followed by the symbol for the operator being defined. Like any other function, an overloaded operator has a return type and a parameter list.
Box operator+(const Box&);
declares the addition operator that can be used to add two Box objects and returns final Box object. Most overloaded operators may be defined as ordinary non-member functions or as class member functions. In case we define above function as non-member function of a class then we would have to pass two arguments for each operand as follows −
Box operator+(const Box&, const Box&);
Following is the example to show the concept of operator over loading using a member function. Here an object is passed as an argument whose properties will be accessed using this object, the object which will call this operator can be accessed using this operator as explained below −
#include <iostream> using namespace std; class Box { public: double getVolume(void) { return length * breadth * height; } void setLength( double len ) { length = len; } void setBreadth( double bre ) { breadth = bre; } void setHeight( double hei ) { height = hei; } // Overload + operator to add two Box objects. Box operator+(const Box& b) { Box box; box.length = this->length + b.length; box.breadth = this->breadth + b.breadth; box.height = this->height + b.height; return box; } private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box }; // Main function for the program int main() { Box Box1; // Declare Box1 of type Box Box Box2; // Declare Box2 of type Box Box Box3; // Declare Box3 of type Box double volume = 0.0; // Store the volume of a box here // box 1 specification Box1.setLength(6.0); Box1.setBreadth(7.0); Box1.setHeight(5.0); // box 2 specification Box2.setLength(12.0); Box2.setBreadth(13.0); Box2.setHeight(10.0); // volume of box 1 volume = Box1.getVolume(); cout << "Volume of Box1 : " << volume <<endl; // volume of box 2 volume = Box2.getVolume(); cout << "Volume of Box2 : " << volume <<endl; // Add two object as follows: Box3 = Box1 + Box2; // volume of box 3 volume = Box3.getVolume(); cout << "Volume of Box3 : " << volume <<endl; return 0; }
When the above code is compiled and executed, it produces the following result −
Volume of Box1 : 210 Volume of Box2 : 1560 Volume of Box3 : 5400
Overloadable/Non-overloadableOperators
Following is the list of operators which can be overloaded −
+ | - | * | / | % | ^ |
& | | | ~ | ! | , | = |
< | > | <= | >= | ++ | -- |
<< | >> | == | != | && | || |
+= | -= | /= | %= | ^= | &= |
|= | *= | <<= | >>= | [] | () |
-> | ->* | new | new [] | delete | delete [] |
Following is the list of operators, which can not be overloaded −
:: | .* | . | ?: |
Operator Overloading Examples
Here are various operator overloading examples to help you in understanding the concept.
Unary Operators Overloading in C++
The unary operators operate on a single operand and following are the examples of Unary operators −
- The increment (++) and decrement (--) operators.
- The unary minus (-) operator.
- The logical not (!) operator.
The unary operators operate on the object for which they were called and normally, this operator appears on the left side of the object, as in !obj, -obj, and ++obj but sometime they can be used as postfix as well like obj++ or obj--.
Following example explain how minus (-) operator can be overloaded for prefix as well as postfix usage.
When the above code is compiled and executed, it produces the following result −#include <iostream> using namespace std; class Distance { private: int feet; // 0 to infinite int inches; // 0 to 12 public: // required constructors Distance() { feet = 0; inches = 0; } Distance(int f, int i) { feet = f; inches = i; } // method to display distance void displayDistance() { cout << "F: " << feet << " I:" << inches <<endl; } // overloaded minus (-) operator Distance operator- () { feet = -feet; inches = -inches; return Distance(feet, inches); } }; int main() { Distance D1(11, 10), D2(-5, 11); -D1; // apply negation D1.displayDistance(); // display D1 -D2; // apply negation D2.displayDistance(); // display D2 return 0; }
F: -11 I:-10 F: 5 I:-11
Hope above example makes your concept clear and you can apply similar concept to overload Logical Not Operators (!).
Binary Operators Overloading in C++
The binary operators take two arguments and following are the examples of Binary operators. You use binary operators very frequently like addition (+) operator, subtraction (-) operator and division (/) operator.
Following example explains how addition (+) operator can be overloaded. Similar way, you can overload subtraction (-) and division (/) operators.
#include <iostream> using namespace std; class Box { double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box public: double getVolume(void) { return length * breadth * height; } void setLength( double len ) { length = len; } void setBreadth( double bre ) { breadth = bre; } void setHeight( double hei ) { height = hei; } // Overload + operator to add two Box objects. Box operator+(const Box& b) { Box box; box.length = this->length + b.length; box.breadth = this->breadth + b.breadth; box.height = this->height + b.height; return box; } }; // Main function for the program int main() { Box Box1; // Declare Box1 of type Box Box Box2; // Declare Box2 of type Box Box Box3; // Declare Box3 of type Box double volume = 0.0; // Store the volume of a box here // box 1 specification Box1.setLength(6.0); Box1.setBreadth(7.0); Box1.setHeight(5.0); // box 2 specification Box2.setLength(12.0); Box2.setBreadth(13.0); Box2.setHeight(10.0); // volume of box 1 volume = Box1.getVolume(); cout << "Volume of Box1 : " << volume <<endl; // volume of box 2 volume = Box2.getVolume(); cout << "Volume of Box2 : " << volume <<endl; // Add two object as follows: Box3 = Box1 + Box2; // volume of box 3 volume = Box3.getVolume(); cout << "Volume of Box3 : " << volume <<endl; return 0; }
When the above code is compiled and executed, it produces the following result −
Volume of Box1 : 210 Volume of Box2 : 1560 Volume of Box3 : 5400
Overloading typecasts
you learned that C++ allows you to convert one data type to another. The following example shows an int being converted into a double:
C++ already knows how to convert between the built-in data types. However, it does not know how to convert any of our user-defined classes. That’s where overloading the typecast operators comes into play.
Overloading the typecast operators allows us to convert our class into another data type. Take a look at the following class:
This class is pretty simple: it holds some number of cents as an integer, and provides access functions to get and set the number of cents. It also provides a constructor for converting an int into a Cents.
If we can convert an int into a Cents, then doesn’t it also make sense for us to be able to convert a Cents back into an int? In some cases, this might not be true, but in this case, it does make sense.
In the following example, we have to use getCents() to convert our Cents variable back into an integer so we can print it using printInt():
If we have already written a lot of functions that take integers as parameters, our code will be littered with calls to getCents(), which makes it more messy than it needs to be.
To make things easier, we can overload the int typecast, which will allow us to cast our Cents class directly into an int. The following example shows how this is done:
There are two things to note:
- To overload the function that casts our class to an int, we write a new function in our class called operator int(). Note that there is a space between the word operator and the type we are casting to.
- Casting operators do not have a return type. C++ assumes you will be returning the correct type.
Now in our example, we can call printInt() like this:
The compiler will first note that function printInt takes an integer parameter. Then it will note that variable cents is not an int. Finally, it will look to see if we’ve provided a way to convert a Cents into an int. Since we have, it will call our operator int() function, which returns an int, and the returned int will be passed to printInt().
We can now also explicitly cast our Cents variable to an int:
You can overload cast operators for any data type you wish, including your own user-defined data types!
Here’s a new class called Dollars that provides an overloaded Cents cast operator:
This allows us to convert a Dollars object directly into a Cents object! This allows you to do something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
class Cents
{
private:
int m_cents;
public:
Cents(int cents = 0)
{
m_cents = cents;
}
// Overloaded int cast
operator int() { return m_cents; }
int getCents() { return m_cents; }
void setCents(int cents) { m_cents = cents; }
};
class Dollars
{
private:
int m_dollars;
public:
Dollars(int dollars=0)
{
m_dollars = dollars;
}
// Allow us to convert Dollars into Cents
operator Cents() { return Cents(m_dollars * 100); }
};
void printCents(Cents cents)
{
std::cout << cents; // cents will be implicitly cast to an int here
}
int main()
{
Dollars dollars(9);
printCents(dollars); // dollars will be implicitly cast to a Cents here
return 0;
}
|
String Manipulation using Operator Overloading
C++ allows us the facility of manipulate strings using the concept of operator overloading.
For example we can overload + operator to concate two strings. We can overload == operator to compare two strings.
Consider Following Example in which we overload + operator to concate two strings.
For example we can overload + operator to concate two strings. We can overload == operator to compare two strings.
Consider Following Example in which we overload + operator to concate two strings.
#include<iostream.h>
#include<string.h>
class string
{
char *name;
int length;
public:
string()
{
length=0;
name = new char[length+1];
}
string(char *n)
{
length=strlen(n);
name= new char [length+1];
strcpy(name,n);
}
void display()
{
cout<<"String:"<<name;
}
string operator+(string s)
{
string temp;
strcpy(temp.name,name);
strcat(temp.name,s.name);
return temp;
}
};
int main()
{
string s1("Hello");
string s2("Welcome");
string s3;
s1.display();
s2.display();
s3=s1+s2;
s3.display();
return 0;
}
#include<string.h>
class string
{
char *name;
int length;
public:
string()
{
length=0;
name = new char[length+1];
}
string(char *n)
{
length=strlen(n);
name= new char [length+1];
strcpy(name,n);
}
void display()
{
cout<<"String:"<<name;
}
string operator+(string s)
{
string temp;
strcpy(temp.name,name);
strcat(temp.name,s.name);
return temp;
}
};
int main()
{
string s1("Hello");
string s2("Welcome");
string s3;
s1.display();
s2.display();
s3=s1+s2;
s3.display();
return 0;
}
Addition of two matrices using operator overloading - C++
#include<iostream>
using namespace std;
class Matrix
{
int a[3][3];
public:
void accept();
void display();
void operator +(Matrix x);
};
void Matrix::accept()
{
cout<<"\n Enter Matrix Element (3 X 3) : \n";
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
cout<<" ";
cin>>a[i][j];
}
}
}
void Matrix::display()
{
for(int i=0; i<3; i++)
{
cout<<" ";
for(int j=0; j<3; j++)
{
cout<<a[i][j]<<"\t";
}
cout<<"\n";
}
}
void Matrix::operator +(Matrix x)
{
int mat[3][3];
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
mat[i][j]=a[i][j]+x.a[i][j];
}
}
cout<<"\n Addition of Matrix : \n\n";
for(int i=0; i<3; i++)
{
cout<<" ";
for(int j=0; j<3; j++)
{
cout<<mat[i][j]<<"\t";
}
cout<<"\n";
}
}
int main()
{
Matrix m,n;
m.accept(); // Accepting Rows
n.accept(); // Accepting Columns
cout<<"\n First Matrix : \n\n";
m.display(); // Displaying First Matrix
cout<<"\n Second Matrix : \n\n";
n.display(); // Displaying Second Matrix
m+n; // Addition of Two Matrices. Overloaded '+' Operator
return 0;
}
using namespace std;
class Matrix
{
int a[3][3];
public:
void accept();
void display();
void operator +(Matrix x);
};
void Matrix::accept()
{
cout<<"\n Enter Matrix Element (3 X 3) : \n";
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
cout<<" ";
cin>>a[i][j];
}
}
}
void Matrix::display()
{
for(int i=0; i<3; i++)
{
cout<<" ";
for(int j=0; j<3; j++)
{
cout<<a[i][j]<<"\t";
}
cout<<"\n";
}
}
void Matrix::operator +(Matrix x)
{
int mat[3][3];
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
mat[i][j]=a[i][j]+x.a[i][j];
}
}
cout<<"\n Addition of Matrix : \n\n";
for(int i=0; i<3; i++)
{
cout<<" ";
for(int j=0; j<3; j++)
{
cout<<mat[i][j]<<"\t";
}
cout<<"\n";
}
}
int main()
{
Matrix m,n;
m.accept(); // Accepting Rows
n.accept(); // Accepting Columns
cout<<"\n First Matrix : \n\n";
m.display(); // Displaying First Matrix
cout<<"\n Second Matrix : \n\n";
n.display(); // Displaying Second Matrix
m+n; // Addition of Two Matrices. Overloaded '+' Operator
return 0;
}
Output:

ARITHMETIC OPERATION ON COMPLEX NUMBERS USING FUNCTION OVERLOADING
Program Description
The program demonstrates the implementation of complex number class and performs simple arithmetic operation using operator overloading.The program supports only floating point value for demonstration purposes.
The program also uses the math library for power function;therefore make sure to link it as well while compiling.
The command to compile this file would be of the form:
g++ complex.cpp -o complex -lm
where complex.cpp is the name of the source file.
Since we are using math library in the program we need to explicitly link it using the -l flag at the command line.
The program also uses the math library for power function;therefore make sure to link it as well while compiling.
The command to compile this file would be of the form:
g++ complex.cpp -o complex -lm
where complex.cpp is the name of the source file.
Since we are using math library in the program we need to explicitly link it using the -l flag at the command line.
Program
/****************************************************************** * code.cheraus.com * * Arithmetic operation on complex numbers using function overloading * ********************************************************************/ #include<iostream> #include<cmath> using namespace std; //class definition for complex number class complex{ private: float real; //stores the real part float img; //stores the complex part public: void getdata(); //takes user input void display(); //display the complex number //constructor for initialization complex() { real=img=0; } //function declarations(prototypes) complex operator+ (complex c1); complex operator- (complex c1); complex operator* (complex c1); complex operator/ (complex c1); }; //Function definitions for the declared functions in the class /* Function definition for display of complex number This function displays the complex complex number in a+bi form,where "a" is real part and "b" is the imaginary part. */ void complex::display() { cout<<"("<<real<<")"<<"+"<<"("<<img<<")"<<"i"; } /* Function definition for getdata() This function takes the data from the user to store in the complex number object. */ void complex::getdata() { cout<<"Enter the real and img of complex no.\n"; cout<<"Real : "; cin>>real; cout<<"Img : "; cin>>img; } /* Function definition for operator "/" This overloads the "/" operator to perform division of two complex numbers. It returns the resultant complex number. */ complex complex::operator/ (complex c1) { complex div; div.real = ((real*c1.real)+(img*c1.img))/(pow(c1.real,2)+pow(c1.img,2)); div.img = ((img*c1.real)-(real*c1.img))/(pow(c1.real,2)+pow(c1.img,2)); return(div); } /* Function definition for operator "*" This overloads the "*" operator to perform multiplication of two complex numbers. It returns the resultant complex number. */ complex complex::operator* (complex c1) { complex mul; mul.real = ((real*c1.real)-(img*c1.img)); mul.img = ((real*c1.img)+(c1.real*img)); return(mul); } /* Function definition for operator "-" This overloads the "*" operator to perform subtraction of two complex numbers. It returns the resultant complex number. */ complex complex::operator- (complex c1) { complex sub; sub.real = real - c1.real; sub.img = img - c1.img; return(sub); } /* Function definition for operator "+" This overloads the "*" operator to perform addition of two complex numbers. It returns the resultant complex number. */ complex complex::operator+ (complex c1) { complex add; add.real = real + c1.real; add.img = img + c1.img; return(add); } //start of main function int main() { complex a,b,c; //creation of objects int opt,opt1=1; while(opt1==1) { a.getdata(); //taking data from user b.getdata(); //displaying the menu for the user cout<<"\n\t\t\t--Main Menu--\n\t1.Addition\n\t2.Subtraction\n\t3.Multiplication"; cout<<"\n\t4.Division\n\t5.Exit\n\t\t---Enter your choice-->"; //taking user choice cin>>opt; //handling the user option switch(opt) { case 1://using the operator overloading to perform addition c = a+b; cout<<"\n\n"; //displaying the output in user friendly format a.display(); cout<<" + "; b.display(); cout<<" = "; c.display(); break; case 2://using the operator overloading to perform subtraction c = a-b; //printing the output in user friendly format cout<<"\n\n"; a.display(); cout<<" - "; b.display(); cout<<" = "; c.display(); break; case 3://using the operator overloading to perform multiplication c = a*b; //printing the output in user friendly format cout<<"\n\n"; a.display(); cout<<" * "; b.display(); cout<<" = "; c.display(); break; case 4://using the operator overloading to perform division c = a/b; //printing the output in user friendly format cout<<"\n\n"; a.display(); cout<<" / "; b.display(); cout<<" = "; c.display(); break; case 5: return 0; default: cout<<"\nInvalid choice.....try again\n"; break; } cout<<"\n\n\nDo you wish to continue(Press 1 to continue)"; cin>>opt1; } return 0; }
Output
Enter the real and img of complex no.
Real : 1
Img : 2
Enter the real and img of complex no.
Real : 3
Img : 4
--Main Menu--
1.Addition
2.Subtraction
3.Multiplication
4.Division
5.Exit
---Enter your choice-->1
(1)+(2)i + (3)+(4)i = (4)+(6)i
Do you wish to continue(Press 1 to continue)1
Enter the real and img of complex no.
Real : 1
Img : 2
Enter the real and img of complex no.
Real : 3
Img : 4
--Main Menu--
1.Addition
2.Subtraction
3.Multiplication
4.Division
5.Exit
---Enter your choice-->2
(1)+(2)i - (3)+(4)i = (-2)+(-2)i
Do you wish to continue(Press 1 to continue)1
Enter the real and img of complex no.
Real : 1
Img : 2
Enter the real and img of complex no.
Real : 3
Img : 4
--Main Menu--
1.Addition
2.Subtraction
3.Multiplication
4.Division
5.Exit
---Enter your choice-->3
(1)+(2)i * (3)+(4)i = (-5)+(10)i
Do you wish to continue(Press 1 to continue)1
Enter the real and img of complex no.
Real : 2
Img : 3
Enter the real and img of complex no.
Real : 4
Img : 5
--Main Menu--
1.Addition
2.Subtraction
3.Multiplication
4.Division
5.Exit
---Enter your choice-->4
(2)+(3)i / (4)+(5)i = (0.560976)+(0.0487805)i
Do you wish to continue(Press 1 to continue)2
Comments
Post a Comment