Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It's possible to make that work, but not via overloading <code>static_cast&lt;&gt;()</code>. You do so by overloading the typecast operator:</p> <pre><code>class Square { public: Square(int side) : side(side) {} operator int() const { return side * side; } // overloaded typecast operator private: int side; }; // ... // Compiler calls Square::operator int() to convert aSquare into an int cout &lt;&lt; static_cast&lt;int&gt;(aSquare) &lt;&lt;endl; </code></pre> <p>Beware that overloaded typecast operators more often than not tend to do more harm than good. They make lots of nonsensical implicit cast operations possible. When you read this code snippet below, do you think "a is going to get the area of s"?</p> <pre><code>Square aSquare; int a = aSquare; // What the heck does this do? </code></pre> <p>I certainly don't. This makes way more sense and is much more readable:</p> <pre><code>Square aSquare; int a = aSquare.GetArea(); </code></pre> <p>Not to mention that typically you want to be able to access other information about <code>Square</code>, like <code>GetSide()</code> or <code>GetApothem()</code> or <code>GetPerimeter()</code> or whatever. <code>operator int()</code> obviously can return only one <code>int</code>, and you can't have multiple <code>operator int()</code>s as members of a class.</p> <p>Here's another situation where the <code>operator int()</code> makes code that compiles yet makes no sense whatsoever:</p> <pre><code>Square s; if(s &gt; 42) {} // Huh?! </code></pre> <p>What does it mean for a <code>Square</code> to be greater than 42? It's nonsense, but with the <code>operator int()</code> the code above will compile as <code>Shape</code> is now convertible to an <code>int</code> which can be compared to another <code>int</code> with a value <code>4</code>.</p> <p>So don't write typecast operators like that. In fact if you're overloading typecast operators you may want to think twice about what you're doing. There's actually only a few cases where overloading the typecast operator is useful in modern C++ (e.g. <a href="http://www.artima.com/cppsource/safebool2.html" rel="noreferrer">the safe bool idiom</a>).</p>
    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. 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