What is function overloading and operator overloading? - C++

What is operator overloading in C++?

- C++ provides ability to overload most operators so that they perform special operations relative to classes. For example, a class String can overload the + operator to concatenate two strings.
- When an operator is overloaded, none of its original meanings are lost. Instead, the type of objects it can be applied to is expanded. By overloading the operators, we can use objects of classes in expressions in just the same way we use C++’s built-in data types.
- Operators are overloaded by creating operator functions. An operator function defines the operations that the overloaded operator will perform on the objects of the class. An operator function is created using the keyword operator.
- For example: Consider class String having data members char *s, int size, appropriate function members and overloaded binary operator + to concatenate two string objects.
class String
{
   char *s;
   int sz;
   public:
       String(int n)
       {
          size = n;
          s = new char [n];
       }
       void accept()
       {
          cout <<”\n Enter String:”;
          cin.getline(s, sz);
       }
       void display()
       {
          cout<<”The string is: ”<<s;
       }
       String operator +(String s2)   // ‘+’ operator overloaded
       {
          String ts(sz + s2.sz);
          for(int i = 0; s[i]!=’\0’;i++)
          ts.s[i] = s[i];
          for(int j = 0; s2.s[j]!=’\0’; i++, j++)
          ts.s[i] = s2.s[j];
          ts.s[i] = ‘\0’;
          return ts;
       }
};

int main()
{
   String s1, s2, s3;
   s1.accept();
   s2.accept();
   s3 = s1 + s2;   //call to the overloaded ‘+’ operator
   s3.display();
}
- If you pass strings “Hello” and “World” for s1 and s2 respectively, it will concatenate both into s3 and display output as “HelloWorld”
Operator overloading can also be achieved using friend functions of a class.
What is overloading unary operator? - C++
What is overloading unary operator? - Unary operators are those which operate on a single variable....
Difference between overloaded functions and overridden functions
Difference between overloaded functions and overridden functions - Overloading is a static or compile-time binding and Overriding is dynamic or run-time binding....
What is function overloading and operator overloading?
What is function overloading and operator overloading? - Function overloading: A feature in C++ that enables several functions of the same name can be defined with different types of parameters or different number of parameters...
Post your comment