Overloading and its Types
Overloading and its Types
When more than one definition for a function name or an operator in the same scope is specified, that means, function overloading or operator overloading.
An overloaded declaration is that declaration which has been declared with the same name as a previously declared the same scope, except that both declarations have different types.
When an overloaded function name or operator is called, the compiler determines the most appropriate definition to use by comparing the argument types used to call the function or operator with the parameter types specified in the definitions.
Function overloading means overloading function name ‘fun’ by declaring more than one function with the name ‘fun’ in the same scope. The declarations of ‘fun’ must differ from each other by the types and the number of arguments in the argument list.
For Example,
void print(int i) {
cout << " printing integer value " << i << endl;
}
void print(double f) {
cout << " printing float value " << f << endl;
}
void print(char* c) {
cout << " printing character value " << c << endl;
}
void main() {
print(10);
print(10.10);
print("ten");
}
Output:
printing integer value 10
printing float value 10.1
printing character value ten
The mechanism of giving special meanings to an operator is known as operator overloading. Overloaded operators are implemented as functions and can be member functions or global functions. Operator overloading involving vector types is not supported.
An overloaded operator is called an operator function. 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. For example the following c++ code illustrates the operator overloading of ‘+’.
class cplx
{
double real,
img;
public:
cplx( double real = 0., double img = 0.); // constructor
cplx operator+(const cplx&) const; // operator+()
};
// define constructor
cplx::cplx( double r, double i )
{
real = r; img = i;
}
// define overloaded + (plus) operator
cplx cplx::operator+ (const cplx& c) const
{
cplx result;
result.real = (this->real + c.real);
result.img = (this->img + c.img);
return result;
}
int main()
{
cplx x(4,4);
cplx y(6,6);
cplx z = x + y; // calls complx::operator+()
}
Posted in Computer Science, Information Technology, Object Oriented Programming, Object Oriented Programming |
