DEFINITION 15: OVERLOADING - PRATMG/2143-OOP-Tamang GitHub Wiki
Function overloading is a feature of object oriented programming in which two or more functions with the same name but different parameters can exist. Function Overloading occurs when a function name is overloaded with different jobs. The "Function" name should be the same in Function Overloading, but the arguments should be different. Function overloading is an example of a polymorphism feature in C++.
#include <iostream>
using namespace std;
void print(int i) {
cout << " Here is int " << i << endl;
}
void print(double f) {
cout << " Here is float " << f << endl;
}
void print(char const *c) {
cout << " Here is char* " << c << endl;
}
int main() {
print(10);
print(10.10);
print("ten");
return 0;
}
We can make operators in C++ work for user-defined classes. This means that C++ can provide operators with a special meaning for a data type; this is known as operator overloading. For example, in a class like String, we can overload the operator '+' so that we can concatenate two strings by simply using +. Other classes in which arithmetic operators can be overloaded include Complex Number, Fractional Number, Big Integer, and so on.
#include<iostream>
using namespace std;
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i =0) {real = r; imag = i;}
// This is automatically called when '+' is used with
// between two Complex objects
Complex operator + (Complex const &obj) {
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print() { cout << real << " + i" << imag << endl; }
};
int main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2; // An example call to "operator+"
c3.print();
}
Reference: