C++ Overloading (Operator and Function)
Overloading
• 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.
• 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 arguments and
obviously different definition (implementation).
Cont.
• When you call an overloaded function 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.
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 can not 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:
Example
Output
• 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&);
Cont.
• 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.
Cont.
Cont.
Output
• 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
Unary Operator Overloading
Cont.
Binary Operator overloading
Cont.
Relational operators overloading in C++
Cont.
Thanks