Overloading

Overloading
An overloaded declaration is a declaration that had been declared with the same name as a previously declared declaration in the same scope, except that both declarations have different types.
If you call an overloaded function name or operator, the compiler determines the most appropriate definition to use by comparing the argument types you 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
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 overloading respectively.
Function overloading or Method overloading
Function overloading means two or more functions can have the same name but either the number of arguments or the data type of arguments has to be different. Return type has no role because function will return a value when it is called and at compile time compiler will not be able to determine which function to call. In the given example in our code we make two functions one for adding two integers and other for adding two floats but they have same name and in the second program we make two functions with identical names but pass them different number of arguments. Function overloading is also known as compile time polymorphism.
For example, a print function that takes a string (or char *) argument performs very different tasks than one that takes an argument of type double. Overloading permits uniform naming and prevents programmers from having to invent names such as print_sz or print_d. The following table shows what parts of a function declaration C++ uses to differentiate between groups of functions with the same name in the same scope.
Overloading Consideration

Function Declaration Element

Used for Overloading

Function return type

No

Number of arguments

Yes

Type of arguments

Yes

Presence or absence of ellipsis

Yes

Use of typedef names

No

Unspecified array bounds

No

const or volatile (see below)

Yes


Although functions can be distinguished on the basis of return type, they cannot be overloaded on this basis. Const or volatile are only used as a basis for overloading if they are used in a class to apply to the this pointer for the class, not the function's return type. In other words, overloading applies only if the const or volatile keyword follows the function's argument list in the declaration.
How function calls are matched with overloaded functions
Making a call to an overloaded function results in one of three possible outcomes:-
1) A match is found. The call is resolved to a particular overloaded function.
2) No match is found. The arguments can not be matched to any overloaded function.
3) An ambiguous match is found. The arguments matched more than one overloaded function.
Ways to overload a Function
1. By changing number of Arguments
2. By having different types of argument
Changing number of Arguments
In this function overloading we define two functions with same names but different number of parameters of the same type. For example, in the given program we have made two sum() functions to return of two and three integers : -
#include< iostream.h >
#include< conio.h >
class func
{
public:
void sum(int x)
{cout< void sum(int x,int y)
{cout< };
void main()
{
func a;
a.sum(10);
a.sum(20,30);
getch();
}
Output: - 102030
Different Datatype of Arguments
In this type of overloading we define two or more functions with same name and same number of parameters, but the type of parameter is different. For example in this program, we have three print() function and one arguments.
#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;
pd.print(5);
pd.print(500.263);
pd.print("Hello C++");
return 0;
}
Output: -
Printing int: 5
Printing float: 500.263
Printing character: Hello C++
Operator overloading
In C++ the overloading principle applies not only to functions, but to operators too. That is, of operators can be extended to work not just with built-in types but also classes. A programmer can provide his or her own operator to a class by overloading the built-in operator to perform some specific computation when the operator is used on objects of that class. Is operator overloading really useful in real world implementations? It certainlly can be, making it very easy to write code that feels natural. On the other hand, operator overloading, like any advanced C++ feature, makes the language more complicated.
Operators overloading in C++:
1. 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.
2. 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.
3. Operator overloading involving vector types is not supported.
4. An overloaded operator is called an operator function. You declare an operator function with the keyword operator preceding the operator. Overloaded operators are distinct from overloaded functions, but like overloaded functions, they are distinguished by the number and types of operands used with the operator.
5. Consider the standard + (plus) operator. When this operator is used with operands of different standard types, the operators have slightly different meanings. For example, the addition of two integers is not implemented in the same way as the addition of two floating-point numbers. C++ allows you to define your own meanings for the standard C++ operators when they are applied to class types. In the following example, a class called complx is defined to model complex numbers, and the + (plus) operator is redefined in this class to add two complex numbers.
6. You can overload any of the following operators:
+ - * / % ^ & | ~
! = < > += -= *= /= %=
^= &= |= << >> <<= >>= == !=
<= >= && || ++ -- , ->* ->
( ) [ ] new delete new[] delete[]

7.You can overload both the unary and binary forms of the following operators:
+ - * &

8.You cannot overload the following operators:
. .* :: ?:

9.You cannot overload the preprocessor symbols # and ##.
10. An operator function can be either a nonstatic member function, or a nonmember function with at least one parameter that has class, reference to class, enumeration, or reference to enumeration type.
11. You cannot change the precedence, grouping, or the number of operands of an operator.
12. An overloaded operator (except for the function call operator) cannot have default arguments or an ellipsis in the argument list.
13. You must declare the overloaded =, [], (), and -> operators as nonstatic member functions to ensure that they receive lvalues as their first operands.
14.The operators new, delete, new[], and delete[] do not follow the general rules described in this section.
15.All operators except the = operator are inherited.
Operator Overloading Examples:
Here are various operator overloading examples to help you in understanding the concept.
1. Unary operators overloading
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.
#include < iostream >
using namespace std;
class Distance
{
private:
int feet;
int inches;
public:
Distance(){
feet = 0;
inches = 0;
}
Distance(int f, int i){
feet = f;
inches = i;
}
void displayDistance()
{
cout << "F: " << feet << " I:" << inches < }
Distance operator- ()
{
feet = -feet;
inches = -inches;
return Distance(feet, inches);
}
};
int main()
{
Distance D1(11, 10), D2(-5, 11);
-D1;
D1.displayDistance();
-D2;
D2.displayDistance();
return 0;
}
Output: -
F: -11 I:-10
F: 5 I:-11
2. Binary operators overloading
The unary 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;
double breadth;
double height;
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;
}
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;
}
};
int main( )
{
Box Box1;
Box Box2;
Box Box3;
double volume = 0.0;
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume < volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume < Box3 = Box1 + Box2;
volume = Box3.getVolume();
cout << "Volume of Box3 : " << volume < return 0;
}
Output: -
Volume of Box1 : 210
Volume of Box2 : 1560
Volume of Box3 : 5400


Free Web Hosting