Creating two or more members having the same name but different in number or type of parameter is known as overloading.
C++ allows the overloading of:-
- methods,
- constructors, and
- indexed properties
and is of two types:-
- Function overloading - having two or more function with the same name, but different in parameters.
CODE:
class Cal {
public:
static int add(int a,int b){
return a + b;
}
static int add(int a, int b, int c)
{
return a + b + c;
}
};
int main(void) {
Cal C; // class object declaration.
cout<<C.add(10, 20)<<endl;
cout<<C.add(12, 20, 23);
return 0;
}
- Operator overloading - operator is overloaded to provide the special meaning to the user-defined data type. Operator overloading is used to overload or redefines most of the operators available in C++
Some exceptions to this are:-
Scope operator (::)
, Sizeof, member selector(.)
, member pointer, selector(*)
, ternary operator(?:)
There are also some norms associated with overloading operators:-
- Existing operators can only be overloaded.
- The overloaded operator contains at least one operand of the user-defined data type.
- When unary operators are overloaded through a member function take no explicit arguments, but, if they are overloaded by a friend function, takes one argument.
- When binary operators are overloaded through a member function takes one explicit argument, and if they are overloaded through a friend function takes two explicit arguments.
class Test
{
private:
int num;
public:
Test(): num(8){}
void operator ++() {
num = num+2;
}
void Print() {
cout<<"The Count is: "<<num;
}
};
int main()
{
Test tt;
++tt; // calling of a function "void operator ++()"
tt.Print();
return 0;
}