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’
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.
There are various types of operators in C++. In our recent posts, we have covered overloading of a bunch of arithmetic operators. There are some arithmetic operators which perform compound functions. It means they handle more than one mathematical function at a time. The Plus Equal or Addition Assignment Operator or plus equals to operator (+=) is one of these. As the name implies, it adds and assigns the value to the variable at the same time. The plus equal operator is quite often used in programming. We shall learn how to overload it.