Function overloading and Operator overloading

Function overloading and Operator overloading


Function Overloading


  • Doing something in excess is called as overloading.
  • When a function is defined more than one time such that either the number of arguments passed in the functions differ or the data type of arguments passed in the functions differ or both, then this is called function overloading. Function overloading is used to achieve compile time polymorphism.

Example of Function Overloading

class abc
{
private:
int x,y,s;
void fun(int x1,int y1) //fun defined
{
   x = x1; y = y1;
   cout<<x*y<<endl;
}
void fun(int s1) //fun redefined - fun is overloaded
{
s = s1; 
cout<<s*s;
};
void main()
{
abc ob1; 
ob1.fun(2,3); 
ob1.fun(4);
}

Output:
6
16

Operator Overloading


  • Doing something in excess is called as overloading.
  • When an operator is used to operate on objects, in addition to constants and variables, then this is called as operator overloading.


Example of unary operator overloading

class abc
{
private:
int x;
public:
void set(int x1)
{
   x=x1;
}
void show()
{
cout<<x<<“\t”;
}
void operator ++() /*this is called as overloaded operator function*/
{    
x=x+1;
};

void main()
{
abc ob1;
ob1.set(10); 
ob1.show();
ob1++; /*means ob1.++(); overloaded operator function called */
ob1.show();
}

Output: 
10  11


Example of binary operator overloading

class abc
{
private:
int x;
public:
void set(int x1)
{
x=x1;
}

void show()
{
cout<<x<<“\t”;
}

void operator +(abc ob)
{  /*overloaded operator function defined*/
x = x + ob.x; /*This would mean ob1’s x = ob1’s x + ob2’s x */
}
};

void main()
{
abc ob1,ob2;
ob1.set(1); 
ob2.set(2);
ob1+ob2; /*This would mean ob1 . + (ob2); overloaded operator function called */
ob1.show();
}

Output: 3


Comments

Popular posts from this blog

Inline and Friend Operators

Exceptional Handling