Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>You don't need const:</strong></p> <blockquote> <p>@numerical25: Just curious on why a param has to be a const in operation overloading</p> </blockquote> <p>It's not required, but it is a good design decision.</p> <p>See the C++ standard Section 12.8-9:</p> <blockquote> <p>A user-declared copy assignment operator X::operator= is a non-static non-template member function of class X with exactly one parameter of type X, X&amp;, const X&amp;, volatile X&amp; or const volatile X&amp;</p> </blockquote> <hr> <p><strong>I think it's a good idea though:</strong></p> <p>Using a const parameter does seems like a logical design decision to me though because you want to ensure that the other value will not be changed.</p> <p>It tells other people that use your class that you will not be changing the <code>other</code> value when you say something like: <code>myObject = other;</code> and it enforces this so you can't accidentally change <code>other</code>.</p> <p>Also if you allowed non const references to the object as the parameter, then you are limiting the amount of objects that can use your function. If it is const it can be used for parameters that are const and non const. If your parameter is non const it can only be used by parameters that are non const. </p> <hr> <p><strong>const only applies to the current reference, not the object:</strong></p> <blockquote> <p>@numerical25: Isn't when something becomes a const, it is unchangeable for the remainder of the applications life ?? How does this differ in operation overloading ???</p> </blockquote> <p>A const reference is simply that a reference that is const. It does not change the const-ness of the actual object you are passing in.</p> <hr> <p><strong>An example of non-const operator overloading:</strong></p> <p>Here is an example of operator overloading where the parameter is not const.<br> I DO NOT RECOMMEND TO DO THIS THOUGH:</p> <pre><code>class B { public: const B&amp; operator=(B&amp; other) { other.x = 3; x = other.x; return *this; } int x; }; void main(int argc, char** argv[]) { B a; a.x = 33; B b; b.x = 44; a = b;//both a and b will be changed return 0; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload