tag:blogger.com,1999:blog-865923359735383241.post5539681006833167518..comments2023-10-29T07:27:09.012-06:00Comments on Ccna final exam - java, php, javascript, ios, cshap all in one: Why doesn"t Java offer operator overloading?Unknownnoreply@blogger.comBlogger1125tag:blogger.com,1999:blog-865923359735383241.post-42339869037354756102012-06-11T22:06:10.599-06:002012-06-11T22:06:10.599-06:00Assuming that the SCdF wanted to overwrite the pre...Assuming that the SCdF wanted to overwrite the previous value of the object refered to by 'a', then a member function would have to be invoked.<br /><br /> Complex a, b, c;<br /> ..<br /> a = b.add(c)<br /><br /><br />In C++, this expression tells the compiler to create 3 objects on the stack, perform addition, and copy the resultant value from the temporary object into the existing object 'a'.<br /><br />However, in java, operator= doesn't perform value copy for reference types, and users can only create new reference types, not value types. So for a user defined type named 'Complex', assignment means to copy a reference to an existing value.<br /><br />consider instead:<br /><br />b.set(1, 0); // initialize to real number '1'<br />a = b; <br />b.set(2, 0);<br />assert( !a.Equals(b) );<br /><br /><br />In C++, this copies the value, so the comparison will result not-equal. In Java, operator= performs reference copy, so 'a' and 'b' are now refering to the same value. As a result, the comparison will produce 'equal', since the object will compare equal to itself.<br /><br />The difference between copies and references only adds to the confusion of operator overloading. As Sebastian mentioned, Java and C# both have to deal with value and reference equality separately -- operator+ would likely deal with values and objects, but operator= is already implemented to deal with references.<br /><br />In C++, you should only be dealing with one kind of comparison at a time, so it can be less confusing. For example, on Complex, operator= and operator== are both working on values -- copying values and comparing values respectively.Userhttps://www.blogger.com/profile/11557173689529910046noreply@blogger.com