Returning a const Object
The preceding definition of Vector::operator+() has a bizarre property. The intended use is this:
net = force1 + force2; // 1: three Vector objects
However, the definition also allows you to use the following:
force1 + force2 = net; // 2: dyslectic programmingcout << (force1 + force2 = net).magval() << endl; // 3: demented programming
Three questions immediately arise. Why would anyone write such statements? Why are they possible? What do they do?
First, there is no sensible reason for writing such code, but not all code is written for sensible reasons. People, even programmers, make mistakes. For instance, if the comparison operator==() were defined for the Vector ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access