Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>UPDATED: a thought</p> <p>Why we need to provide user-defined copy assignment operator? Answer: I think the default behavior of the implicit assignment operator is to re-assign the referenced member variable to refer to another location instead of the semantic in <code>m_characterReference = p_assignator.m_characterReference;</code>. Reference variable for us is a syntactic sugar but for the compiler it is a constant pointer. Thus, the default assignment tries to re-assign this constant pointer.</p> <hr> <p>The two functions <code>CReference::operator char()</code> and <code>CReference::operator=(char)</code> do not represent <em>lvalue</em> and <em>rvalue</em>.</p> <p>As previously mentioned, your main mistake is that you declared the copy assignment operator to return void. Thus, it won't be invoked.</p> <p>For the compiler to execute "s[0] = s[1];" and based on your code, first, s[x] will be converted to CRefernce anonymous objects. Then the compiler search for <code>operator=()</code>. Since you provide <code>operator=(char)</code>, the compiler is "smart" and try to fulfill this assignment. So, it will invoke operator char() first to convert right-hand side (which CReference(s[1]) to char, then invoke operator=(char) function. The expression (s[0] = s[1]) becomes of type char.</p> <p>You can avoid this conversion by modifying your code as</p> <pre><code>class CReference { private: char&amp; m_characterReference; public: // Construct CReference from char&amp; CReference(char &amp;m_initialiser) : m_characterReference(m_initialiser) {} char&amp; operator = (const CReference &amp;r) { m_characterReference = r.m_characterReference; return m_characterReference; } }; </code></pre> <p>The assignment operator returns char if you would like to keep the type of "s1[0] = s1[1]" as character. You should not worry about conversion from char to CReference (in case of s1[0] = s1[1] = s1[2]) since 1-arg constructor will handle this conversion.</p> <p>A simple and clear example that represents lvalue and rvalue is</p> <pre><code>class Point { public: int&amp; x() {return x_value; } int&amp; y() {return y_value; } private: int x_value; int y_value; }; int main() { Point p1; p1.x() = 2; p1.y() = 4; cout &lt;&lt; p1.x() &lt;&lt; endl; cout &lt;&lt; p1.y() &lt;&lt; endl; } </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. This table or related slice is empty.
    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