Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>See this previous answer to a related question. It's a long quote from a Dan Saks article that explains this issue as clearly as anything I've come across:</p> <p><a href="https://stackoverflow.com/questions/612328/difference-between-struct-and-typedef-struct-in-c/612476#612476">Difference between &#39;struct&#39; and &#39;typedef struct&#39; in C++?</a></p> <p>The technique can prevent actual problems (though admittedly rare problems).</p> <p>It's a cheap bit of insurance - it's zero cost at runtime or in code space (the only cost is the few bytes in the source file), but the protection you get is so small that it's uncommon to see someone use it consistently. I have a 'new class' snippet that includes the typedef, but if I actually code up a class from scratch without using the snippet, I almost never bother (or is it remember?) to add the typedef.</p> <p>So I'd say I disagree with most of the opinions given here - it is worth putting those typedefs in, but not enough that I'd give anyone (including myself) grief about not putting them in.</p> <p>I've been asked for an example of how not having a class name typedef'ed can result in unexpected behavior - here's an example lifted more or less from the Saks article:</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; using namespace std; #if 0 // change to #if 1 to get different behavior // imagine that this is buried in some header // and even worse - it gets added to a header // during maintenance... string foo() { return "function foo... \n"; } #endif class foo { public: operator string() { return "class foo...\n"; } }; int main() { string s = foo(); printf( "%s\n", s.c_str()); return 0; } </code></pre> <p>When the function declaration is made visible, the behavior of the program silently changes because there is no name conflict between the function <code>foo</code> and the class <code>foo</code>.</p> <p>However, if you include a "<code>typedef class foo foo;</code>" you'll get a compile time error instead of a silent difference in behavior.</p>
 

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