After a lengthy break, i’m back with my series on object oriented programming in C++ made easy for beginners. As you may recall, I had started this series as a sort of a basic guide for programmers who were just delving into the basics of OOP in C++. I hope by now all of you understand the basic concepts behind classes and how they are used. All of that prior knowledge will be required, as today I am going to be talking about the concept of operator overloading in classes in C++.
Posts Tagged ‘operator overlaoding’
While working with classes, we often want to have the user defined functionalities which help enormously during the rest of the program. When we deal a lot with arrays, we often want to add the contents of two arrays into a single larger array. This could tediously be done by declaring another array of the combined size of the two and adding them one by one in it. The better option to do this is to overload the addition operator ( ) once which saves us doing this process repeatedly if we add two arrays time and again in our program. Let us see how we can do that efficiently.
A week ago, we saw how to overload an assignment operator in object oriented paradigm. As a whole, operator overloading is an important and challenging task. Bjarne Stroustrup, the author and designer of C++ took considerable pain to ensure that user defined types become as close to the built in types as possible. Operator overloading is an offshoot of this. It saves time, energy, resources and many potential dangers to the program. There are certain rules and conventions while overloading operators. Some of them are described in this article.
While working with objects in Object Oriented Paradigm, we often want to implement user defined functionalities. C++ gives us the facility to define the use of the already existing operators by our own choice. One such operator is the assignment or equality operator ( = ). It is used for transferring the contents of one object into another object. It should be defined by the user in his class as a good programming approach and to ensure smooth execution of the program. There are some important things to be kept in mind while overloading assignment operator, described here.
C allows almost all the operators to be overloaded both as member and non-member functions. Up till now we have overloaded all the operators as member functions. Today we shall overload addition operator for our class as a non-member function. We shall also look at the advantages and disadvantages of declaring an overloaded function for the operator as a non-member function.