Whats the purpose of overloading operators? Why would I create a function for ++ if I could use ++ already?
Thanks in advance.
Whats the purpose of overloading operators? Why would I create a function for ++ if I could use ++ already?
Thanks in advance.
>Whats the purpose of overloading operators?
Syntactic sugar, notational convenience, whatever neat little phrase you have for simplifying the programmer's job in reading and writing more intuitive code. Of course, often this convenience is had at the cost of safety.
>Why would I create a function for ++ if I could use ++ already?
You can't use ++ for a linked list, you must use
p = p->next;
However, you can overload the ++ operator for your list class so that p++ performs the same operation as p = p->next underneath the hood. Notational convenience.
-Prelude
My best code is written with the delete key.
Given with the above code we can create idiotic_example objects that hold an int we set. How without overloading ++ can we do this...Code:class idiotic_example { private: int a; public: idiotic_example() : a(0) {} idiotic_example(int x) : a(x) {} };
Now its fairly obvious what that should do. It should increment the This_is_stupid.a and return its old value. Easy enough to write.Code:idiotic_example This_is_stupid; This_is_stupid ++;
Problem solved. Now the ++ can work. But only the postfix form. The prefix form has not been overloaded. ok this was a quick and silly example but once you start writing your own classes you will love operator overloading.Try writing a string class or a bounds checked array class. You will need heavy operator overloading for those and will help you understand its need better.Code:class idiotic_example { private: int a; public: idiotic_example() : a(0) {} idiotic_example(int x) : a(x) {} int operator++ (int x) { int temp = a; ++a; return temp; } };
Free the weed!! Class B to class C is not good enough!!
And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi
Wow, actually understand it. Thanks! This forum rocks!