Hey friends !please explain me this code .. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Hey friends !please explain me this code ..

// Program to explain Overloading of // Unary Minus ( - ) Operator #include <iostream> class Counter { unsigned int count; public: Counter() { count = 0; } Counter( int c ) { count = c; } int getCount() { return count; } void operator -() // prefix { count = -count; } }; void main() { Counter c1(10), c2(20); cout << "\n c1 : " << c1.getCount(); cout << "\n c2 : " << c2.getCount(); -c2; cout << "\n c1 : " << c1.getCount(); cout << "\n -c2 : " << c2.getCount(); return 0; } /* Output: c1 : 10 c2 : 20 c1 : 10 -c2 : 20 */

26th Aug 2018, 4:23 AM
Albert Whittaker :Shaken To Code
Albert Whittaker :Shaken To Code - avatar
2 Answers
+ 7
The method getCount() returns the value of the count member as a signed integer. Thus, your unsigned variable gets converted to the signed form. Now, on calling -c2, the call to the operator-() is made, and your code becomes : c2.operator-(); Now, on printing the values, you get the signed version, and thus, -c2 makes count = -20.
26th Aug 2018, 4:57 AM
Kinshuk Vasisht
Kinshuk Vasisht - avatar
+ 3
Albert Whittaker :fan of DORAEMON one change in code is that it should be int main instead of void main as you have used return 0.. Another thing is that output would be -c2 = -20 instead of 20... I presume it's typo. coming to answer of your query, operator - is overloaded for Counter class and hence you are able to write -c2 (c2 is object of class). without that operator overloading function, -c2 will give error. void is return type expected for your function as you don't want to return anything... just you want to make variable opposite sign.. Operator is keyword and - is the operator which you wanna overload... () indicate no parameters are passed to function.... only line in function body reverse the sign of member variables of class... hope it is clear. feel free to ask for further clarification
26th Aug 2018, 5:01 AM
Ketan Lalcheta
Ketan Lalcheta - avatar