dcsimg

Operator Overloading in C++: Is It Really Necessary?

WEBINAR:
On-Demand

Desktop-as-a-Service Designed for Any Cloud ? Nutanix Frame


Before we answer the question, we must understand the idea of operator overloading. The basic tenet of operator overloading is to give a new meaning to the conventional operations associated with the operator. It simply is another way to call a function but there are some differences. This article explores the concept and its utility in C++ programming.

Operator Overloading

The primary motive of the process of operator overloading is to make the conventional operators work with objects in C++. There are quite a few operators overloaded into the Standard C++ library. Perhaps, the simplest one quickly acquaints with is <<. This is both an insertion operator as well as bitwise left-shift operator. So is >>, the extraction operator as well as bitwise right-shift operator. The idea of overload is imbibed into the C++ language because even simple addition (+) and simple subtraction (-) works according the context of operation. The context of operation is determined by the type of operation, such as integer, floating-point, or pointer arithmetic. We can extend the context by overloading the same operator. For example, we can overload the addition (+) operator to concatenate string objects. There is no virtual limit to making it work according to various contextual extension.

Most operators in C++ can be overloaded and make it work in the context of objects and classes barring a few. It is the responsibility of the compiler to generate appropriate code on the types of operand. Note that an implementation that we do through operator overloading can definitely be done by a similar regular function, but operator overloading adds flavor to the natural syntax of the code. For example, the string class of the Standard Library has a lot of operator overloaded. We can assign values to a string object with the equal operator (=); the plus (+) operator is overloaded to concatenate two strings or a string and a char. It is but natural to think that we should be able to increment the current date of a Date object with the increment operator (++).

These are all possible with operator overloading. To appreciate the idea fully, let us see how the operator overloaded with the string class from the Standard Library works.

Overloaded Operators in the string Class

The string is a template class of the C++ Standard Library. It is used to store and manipulate a sequence of characters in a generic manner. Along with many convenient sets of methods for string creation, manipulation, and destruction, the class overloads a host of operators to make assignment, comparison, concatenation, and array operation look more natural and easier. To give you an idea of how easy the operation apparently seems, here is a quick example.

#include <iostream>
#include <string>
using namespace std;

int main()
{
   string str1 = "OOPs";
   string str2("Hello");
   string str3("  with spaces   ");
   string str4;

   cout<<"Value of str1, str2, str3, str4 :\n"<<str1
      <<endl<<str2<<endl<<str3<<endl<<str4<<endl;

   cout<<"\n str1==str4 is "<<(str1==str4 ? " true" :
      " false")<<endl;
   str4=str1;
   cout<<"\nAfter str4=str1, str1==str4 is
      "<<(str1==str4 ? " true" : " false")<<endl;

   cout<<"\n str1 != str2 is "<<(str1!=str2 ? " true" :
      " false")<<endl;
   cout<<"\n str1 < str2 is "<<(str1<str2 ? " true" :
      " false")<<endl;
   cout<<"\n str1 > str2 is "<<(str1>str2 ? " true" :
      " false")<<endl;
   cout<<"\n str1 < str2 is "<<(str1<str2 ? " true" :
      " false")<<endl;
   cout<<"\n str1 >= str2 is "<<(str1>=str2 ? " true" :
      " false")<<endl;
   cout<<"\n str1 <= str2 is "<<(str1<=str2 ? " true" :
      " false")<<endl;

   str4 = str1 + str3;
   str1 +=" (Object Oriented Programming)";
   cout<<"\n str4 "<<str4;
   cout<<"\n str1 "<<str1;

   return 0;
}

Recall that a string is nothing but an array of characters. Therefore, simple operations such as an assignment, comparison, and so forth, need to be handled more elaborately. It is not the same as we do with primitive data types such as int, float, or char. Therefore, string is made a templated class, and to make it operate like fundamental data types, operators are overloaded according to the context to act with the array of characters. The plus (+) operator concatenates, the equal (=) operator assigns, the equality (==) operator compares, and so on. The operation becomes more convenient to use with natural notational appeal. This is the power of operator overloading.

Operator and Ordinary Function

Operator overloading actually masks the behavior of an ordinary function call. The arguments of the operator function do not appear inside the parenthesis. Instead, they actually surround or stay next to the characters which we typically think of as immutable operators. Ordinary functions are syntactically different from operator functions. An operator function is invoked according to the context associated with the operator. The meaning of the context is determined by the arguments that may surround or stay next to the operator. The compiler recognizes which function to call by the context. For example, if we are use the operator + with integer arguments, the compiler calls the function to perform integer addition. If we use operator + to add floating-point number with integer, the compiler first converts the float value to integer and then call the addition code. Similarly, if we use operator + with a string object argument, the compiler gets the idea from the context about which function to call associated with operator +, defined in the string class.

Understand This...

Operator overloading is not a fun toy to be used indiscriminately, although it may be tempting to create one on even the slightest possible situation at first. Because there is no such code that can be done only with an operator function and not with an ordinary function, there is no reason to overload one just for its exquisiteness. Understand that it simply adds a layer of convenience, another way to call a function. If it does not help make the code easy to write, read, and use, there is no point in overloading an operator.

There is no disadvantage as such to operator overloading and neither does it add anything to the processing power of the code in any way. It is just there as a feature to use for the sake of convenience and another reason to love coding in C++.

Java, another popular object-oriented programming language, does not allow the user to overload any operator but internally overloads them. For example, the String class uses the operator plus (+) for concatenation, equal (=) operator for assignment, and so on.

These features emphasize its utility.

Conclusion

Now, we ask the question again: Is it necessary? The one word answer will be no, it is not, because we can do everything with the ordinary functions that we want to do with an operator function. But then, this feature definitely leverages convenience of the programmer; however, it may not add to the performance. Because the idea of operator overloading is imbibed in every language, C++ opened the gateway for the programmer to use them while other languages guarded it closely. Do not use it, you miss nothing. Use it and you'll love it.



Related Articles

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date