<p>No C++ love when it comes to the "hidden features of" line of questions?  Figured I would throw it out there.  What are some of the hidden features of C++?</p>

[{'answer_id': 75581, 'author': 'neuroguy123', 'author_id': 12529, 'author_profile': 'https://Stackoverflow.com/users/12529', 'pm_score': 2, 'selected': False, 'text': '<p>I\'m not sure about hidden, but there are some <a href="http://en.wikipedia.org/wiki/Duff%27s_device" rel="nofollow noreferrer">interesting</a> <a href="http://en.wikipedia.org/wiki/Template_metaprogramming" rel="nofollow noreferrer">\'tricks\'</a> that probably aren\'t obvious from just reading the spec.</p>\n'}, {'answer_id': 75627, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 6, 'selected': False, 'text': '<blockquote>\n  <p>C++ is a standard, there shouldn\'t be any hidden features...</p>\n</blockquote>\n\n<p>C++ is a multi-paradigm language, you can bet your last money on there being hidden features. One example out of many: <a href="http://en.wikipedia.org/wiki/Template_metaprogramming" rel="nofollow noreferrer">template metaprogramming</a>. Nobody in the standards committee intended there to be a Turing-complete sublanguage that gets executed at compile-time.</p>\n'}, {'answer_id': 75709, 'author': 'Drealmer', 'author_id': 12291, 'author_profile': 'https://Stackoverflow.com/users/12291', 'pm_score': 3, 'selected': False, 'text': '<p>I found this blog to be an amazing resource about the arcanes of C++ : <a href="http://cpptruths.blogspot.com/" rel="nofollow noreferrer">C++ Truths</a>.</p>\n'}, {'answer_id': 75818, 'author': 'sergtk', 'author_id': 13441, 'author_profile': 'https://Stackoverflow.com/users/13441', 'pm_score': 3, 'selected': False, 'text': '<p>There is no hidden features, but the language C++ is very powerful and frequently even developers of standard couldn\'t imagine what C++ can be used for. </p>\n\n<p>Actually from simple enough language construction you can write something very powerful.\nA lot of such things are available at www.boost.org as an examples (and <a href="http://www.boost.org/doc/libs/1_36_0/doc/html/lambda.html" rel="noreferrer">http://www.boost.org/doc/libs/1_36_0/doc/html/lambda.html</a> among them).</p>\n\n<p>To understand the way how simple language constuction can be combined to something powerful it is good to read <a href="https://rads.stackoverflow.com/amzn/click/com/0201734842" rel="noreferrer" rel="nofollow noreferrer">"C++ Templates: The Complete Guide" by David Vandevoorde, Nicolai M. Josuttis</a> and really magic book <a href="https://rads.stackoverflow.com/amzn/click/com/0201704315" rel="noreferrer" rel="nofollow noreferrer">"Modern C++ Design ... " by Andrei Alexandrescu</a>.</p>\n\n<p>And finally, it is difficult to learn C++, you should try to fill it ;)</p>\n'}, {'answer_id': 75849, 'author': 'ugasoft', 'author_id': 10120, 'author_profile': 'https://Stackoverflow.com/users/10120', 'pm_score': 2, 'selected': False, 'text': '<p>There are a lot of "undefined behavior". You can learn how to avoid them reading good books and reading the standards.</p>\n'}, {'answer_id': 75917, 'author': 'Amir', 'author_id': 13480, 'author_profile': 'https://Stackoverflow.com/users/13480', 'pm_score': 1, 'selected': False, 'text': '<p>There are tons of "tricky" constructs in C++.\nThey go from "simple" implementions of <a href="http://www.gamedev.net/reference/programming/features/cppseal/" rel="nofollow noreferrer">sealed/final classes</a> using virtual inheritance.\nAnd get to pretty "complex" meta programming constructs such as Boost\'s <a href="http://www.boost.org/doc/libs/1_36_0/libs/mpl/doc/index.html" rel="nofollow noreferrer">MPL</a> (<a href="http://ubiety.uwaterloo.ca/~tveldhui/papers/Template-Metaprograms/meta-art.html" rel="nofollow noreferrer">tutorial</a>). The possibilities for shooting yourself in the foot are endless, but if kept in check (i.e. seasoned programmers), provide some of the best flexibility in terms of maintainability and performance.</p>\n'}, {'answer_id': 76058, 'author': 'Markowitch', 'author_id': 11964, 'author_profile': 'https://Stackoverflow.com/users/11964', 'pm_score': 3, 'selected': False, 'text': '<blockquote>\n  <p>One example out of many: template\n  metaprogramming. Nobody in the\n  standards committee intended there to\n  be a Turing-complete sublanguage that\n  gets executed at compile-time.</p>\n</blockquote>\n\n<p>Template metaprogramming is hardly a hidden feature. It\'s even in the boost library. See <a href="http://www.boost.org/doc/libs/release/libs/mpl/doc/index.html" rel="nofollow noreferrer">MPL</a>. But if "almost hidden" is good enough, then take a look at the <a href="http://www.boost.org/doc/libs" rel="nofollow noreferrer">boost libraries</a>. It contain many goodies which are not easy accesible without the backing of a strong library.</p>\n\n<p>One example is <a href="http://www.boost.org/doc/libs/release/doc/html/lambda.html" rel="nofollow noreferrer">boost.lambda</a> library, which is interesting since C++ does not have lambda functions in the current standard.</p>\n\n<p>Another example is <a href="http://loki-lib.sourceforge.net/index.php?n=Main.HomePage" rel="nofollow noreferrer">Loki</a>, which "makes extensive use of C++ template metaprogramming and implements several commonly used tools: typelist, functor, singleton, smart pointer, object factory, visitor and multimethods." [<a href="http://en.wikipedia.org/wiki/Loki_%28C%2B%2B%29" rel="nofollow noreferrer">Wikipedia</a>]</p>\n'}, {'answer_id': 76606, 'author': 'MSN', 'author_id': 6210, 'author_profile': 'https://Stackoverflow.com/users/6210', 'pm_score': 6, 'selected': False, 'text': "<p>Lifetime of temporaries bound to const references is one that few people know about. Or at least it's my favorite piece of C++ knowledge that most people don't know about.</p>\n\n<pre><code>const MyClass&amp; x = MyClass(); // temporary exists as long as x is in scope\n</code></pre>\n"}, {'answer_id': 76801, 'author': 'Colin Jensen', 'author_id': 9884, 'author_profile': 'https://Stackoverflow.com/users/9884', 'pm_score': 6, 'selected': False, 'text': "<p>The array operator is associative.</p>\n\n<p>A[8] is a synonym for *(A + 8).  Since addition is associative, that can be rewritten as *(8 + A), which is a synonym for..... 8[A]</p>\n\n<p>You didn't say useful... :-) </p>\n"}, {'answer_id': 77169, 'author': 'Sridhar Iyer', 'author_id': 13820, 'author_profile': 'https://Stackoverflow.com/users/13820', 'pm_score': 2, 'selected': False, 'text': '<p>Most C++ developers ignore the power of template metaprogramming. Check out <a href="http://loki-lib.sourceforge.net/index.php?n=Main.HomePage" rel="nofollow noreferrer">Loki Libary</a>. It implements several advanced tools like typelist, functor, singleton, smart pointer, object factory, visitor and multimethods using template metaprogramming extensively (from <a href="http://en.wikipedia.org/wiki/Loki_(C%2B%2B)" rel="nofollow noreferrer">wikipedia</a>). \nFor most part you could consider these as "hidden" c++ feature.</p>\n'}, {'answer_id': 78128, 'author': 'paercebal', 'author_id': 14089, 'author_profile': 'https://Stackoverflow.com/users/14089', 'pm_score': 7, 'selected': False, 'text': '<p>I agree with most posts there: C++ is a multi-paradigm language, so the "hidden" features you\'ll find (other than "undefined behaviours" that you should avoid at all cost) are clever uses of facilities.</p>\n\n<p>Most of those facilities are not build-in features of the language, but library-based ones.</p>\n\n<p>The most important is the <strong>RAII</strong>, often ignored for years by C++ developers coming from the C world. <strong>Operator overloading</strong> is often a misunderstood feature that enable both array-like behaviour (subscript operator), pointer like operations (smart pointers) and build-in-like operations (multiplying matrices.</p>\n\n<p>The use of <strong>exception</strong> is often difficult, but with some work, can produce really robust code through <strong>exception safety</strong> specifications (including code that won\'t fail, or that will have a commit-like features that is that will succeed, or revert back to its original state).</p>\n\n<p>The most famous of "hidden" feature of C++ is <strong>template metaprogramming</strong>, as it enables you to have your program partially (or totally) executed at compile-time instead of runtime. This is difficult, though, and you must have a solid grasp on templates before trying it.</p>\n\n<p>Other make uses of the multiple paradigm to produce "ways of programming" outside of C++\'s ancestor, that is, C.</p>\n\n<p>By using <strong>functors</strong>, you can simulate functions, with the additional type-safety and being stateful. Using the <strong>command</strong> pattern, you can delay code execution. Most other <strong>design patterns</strong> can be easily and efficiently implemented in C++ to produce alternative coding styles not supposed to be inside the list of "official C++ paradigms".</p>\n\n<p>By using <strong>templates</strong>, you can produce code that will work on most types, including not the one you thought at first. You can increase type safety,too (like an automated typesafe malloc/realloc/free). C++ object features are really powerful (and thus, dangerous if used carelessly), but even the <strong>dynamic polymorphism</strong> have its static version in C++: the <strong>CRTP</strong>.</p>\n\n<p>I have found that most "<em>Effective C++</em>"-type books from Scott Meyers or "<em>Exceptional C++</em>"-type books from Herb Sutter to be both easy to read, and quite treasures of info on known and less known features of C++.</p>\n\n<p>Among my preferred is one that should make the hair of any Java programmer rise from horror: In C++, <strong>the most object-oriented way to add a feature to an object is through a non-member non-friend function, instead of a member-function</strong> (i.e. class method), because:</p>\n\n<ul>\n<li><p>In C++, a class\' interface is both its member-functions and the non-member functions in the same namespace</p></li>\n<li><p>non-friend non-member functions have no privileged access to the class internal. As such, using a member function over a non-member non-friend one will weaken the class\' encapsulation.</p></li>\n</ul>\n\n<p>This never fails to surprise even experienced developers.</p>\n\n<p>(Source: Among others, Herb Sutter\'s online Guru of the Week #84: <a href="http://www.gotw.ca/gotw/084.htm" rel="nofollow noreferrer">http://www.gotw.ca/gotw/084.htm</a> )</p>\n'}, {'answer_id': 78436, 'author': 'Robert', 'author_id': 14364, 'author_profile': 'https://Stackoverflow.com/users/14364', 'pm_score': 5, 'selected': False, 'text': "<p>Oooh, I can come up with a list of pet hates instead:</p>\n\n<ul>\n<li>Destructors need to be virtual if you intend use polymorphically</li>\n<li>Sometimes members are initialized by default, sometimes they aren't</li>\n<li>Local clases can't be used as template parameters (makes them less useful)</li>\n<li>exception specifiers: look useful, but aren't</li>\n<li>function overloads hide base class functions with different signatures.</li>\n<li>no useful standardisation on internationalisation (portable standard wide charset, anyone? We'll have to wait until C++0x)</li>\n</ul>\n\n<p>On the plus side</p>\n\n<ul>\n<li>hidden feature: function try blocks. Unfortunately I haven't found a use for it. Yes I know why they added it, but you have to rethrow in a constructor which makes it pointless.</li>\n<li>It's worth looking carefully at the STL guarantees about iterator validity after container modification, which can let you make some slightly nicer loops.</li>\n<li>Boost - it's hardly a secret but it's worth using.</li>\n<li>Return value optimisation (not obvious, but it's specifically allowed by the standard)</li>\n<li>Functors aka function objects aka operator(). This is used extensively by the STL. not really a secret, but is a nifty side effect of operator overloading and templates.</li>\n</ul>\n"}, {'answer_id': 78484, 'author': 'Jason Mock', 'author_id': 13630, 'author_profile': 'https://Stackoverflow.com/users/13630', 'pm_score': 7, 'selected': False, 'text': "<p>One language feature that I consider to be somewhat hidden, because I had never heard about it throughout my entire time in school, is the namespace alias.  It wasn't brought to my attention until I ran into examples of it in the boost documentation.  Of course, now that I know about it you can find it in any standard C++ reference.</p>\n\n<pre><code>namespace fs = boost::filesystem;\n\nfs::path myPath( strPath, fs::native );\n</code></pre>\n"}, {'answer_id': 78557, 'author': 'shoosh', 'author_id': 9611, 'author_profile': 'https://Stackoverflow.com/users/9611', 'pm_score': 2, 'selected': False, 'text': '<ul>\n<li>pointers to class methods </li>\n<li>The "typename" keyword</li>\n</ul>\n'}, {'answer_id': 78840, 'author': 'Ben', 'author_id': 13950, 'author_profile': 'https://Stackoverflow.com/users/13950', 'pm_score': 8, 'selected': False, 'text': '<p>You can put URIs into C++ source without error.  For example:</p>\n\n<pre><code>void foo() {\n    http://stackoverflow.com/\n    int bar = 4;\n\n    ...\n}\n</code></pre>\n'}, {'answer_id': 132174, 'author': 'bernardn', 'author_id': 21548, 'author_profile': 'https://Stackoverflow.com/users/21548', 'pm_score': -1, 'selected': False, 'text': "<p>Pointer arithmetics.</p>\n\n<p>It's actually a C feature, but I noticed that few people that use C/C++ are really aware it even exists. I consider this feature of the C language truly shows the genius and vision of its inventor.</p>\n\n<p>To make a long story short, pointer arithmetics allows the compiler to perform a[n] as *(a+n) for any type of a. As a side note, as '+' is commutative a[n] is of course equivalent to n[a].</p>\n"}, {'answer_id': 132815, 'author': 'AareP', 'author_id': 11741, 'author_profile': 'https://Stackoverflow.com/users/11741', 'pm_score': 4, 'selected': False, 'text': '<p>Getting rid of forward declarations:</p>\n\n<pre><code>struct global\n{\n     void main()\n     {\n           a = 1;\n           b();\n     }\n     int a;\n     void b(){}\n}\nsingleton;\n</code></pre>\n\n<p>Writing switch-statements with ?: operators:</p>\n\n<pre><code>string result = \n    a==0 ? "zero" :\n    a==1 ? "one" :\n    a==2 ? "two" :\n    0;\n</code></pre>\n\n<p>Doing everything on a single line:</p>\n\n<pre><code>void a();\nint b();\nfloat c = (a(),b(),1.0f);\n</code></pre>\n\n<p>Zeroing structs without memset: </p>\n\n<pre><code>FStruct s = {0};\n</code></pre>\n\n<p>Normalizing/wrapping angle- and time-values:</p>\n\n<pre><code>int angle = (short)((+180+30)*65536/360) * 360/65536; //==-150\n</code></pre>\n\n<p>Assigning references:</p>\n\n<pre><code>struct ref\n{\n   int&amp; r;\n   ref(int&amp; r):r(r){}\n};\nint b;\nref a(b);\nint c;\n*(int**)&amp;a = &amp;c;\n</code></pre>\n'}, {'answer_id': 152659, 'author': 'vividos', 'author_id': 23740, 'author_profile': 'https://Stackoverflow.com/users/23740', 'pm_score': 6, 'selected': False, 'text': "<p>A nice feature that isn't used often is the function-wide try-catch block:</p>\n\n<pre><code>int Function()\ntry\n{\n   // do something here\n   return 42;\n}\ncatch(...)\n{\n   return -1;\n}\n</code></pre>\n\n<p>Main usage would be to translate exception to other exception class and rethrow, or to translate between exceptions and return-based error code handling.</p>\n"}, {'answer_id': 169114, 'author': 'Sumant', 'author_id': 25014, 'author_profile': 'https://Stackoverflow.com/users/25014', 'pm_score': 5, 'selected': False, 'text': '<p>Hidden features:</p>\n\n<ol>\n<li>Pure virtual functions can have implementation. Common example, pure virtual destructor.</li>\n<li><p>If a function throws an exception not listed in its exception specifications, but the function has <code>std::bad_exception</code> in its exception specification, the exception is converted into <code>std::bad_exception</code> and thrown automatically. That way you will at least know that a <code>bad_exception</code> was thrown. Read more <a href="http://cpptruths.blogspot.com/2007/05/use-of-stdbadexception.html" rel="nofollow noreferrer">here</a>.</p></li>\n<li><p>function try blocks</p></li>\n<li><p>The template keyword in disambiguating typedefs in a class template. If the name of a member template specialization appears after a <code>.</code>, <code>-&gt;</code>, or <code>::</code> operator, and that name has explicitly qualified template parameters, prefix the member template name with the keyword template. Read more <a href="http://en.wikibooks.org/wiki/More_C++_Idioms/Policy_Clone" rel="nofollow noreferrer">here</a>.</p></li>\n<li><p>function parameter defaults can be changed at runtime. Read more <a href="http://cpptruths.blogspot.com/2005/07/changing-c-function-default-arguments.html" rel="nofollow noreferrer">here</a>.</p></li>\n<li><p><code>A[i]</code> works as good as <code>i[A]</code></p></li>\n<li><p>Temporary instances of a class can be modified! A non-const member function can be invoked on a temporary object. For example:</p>\n\n<pre><code>struct Bar {\n  void modify() {}\n}\nint main (void) {\n  Bar().modify();   /* non-const function invoked on a temporary. */\n}\n</code></pre>\n\n<p>Read more <a href="http://cpptruths.blogspot.com/2009/08/modifying-temporaries.html" rel="nofollow noreferrer">here</a>.</p></li>\n<li><p>If two different types are present before and after the <code>:</code> in the ternary (<code>?:</code>) operator expression, then the resulting type of the expression is the one that is the most general of the two. For example:</p>\n\n<pre><code>void foo (int) {}\nvoid foo (double) {}\nstruct X {\n  X (double d = 0.0) {}\n};\nvoid foo (X) {} \n\nint main(void) {\n  int i = 1;\n  foo(i ? 0 : 0.0); // calls foo(double)\n  X x;\n  foo(i ? 0.0 : x);  // calls foo(X)\n}\n</code></pre></li>\n</ol>\n'}, {'answer_id': 170597, 'author': 'Sirish', 'author_id': 7965, 'author_profile': 'https://Stackoverflow.com/users/7965', 'pm_score': 5, 'selected': False, 'text': '<p>Array initialization in constructor.\nFor example in a class if we have a array of <code>int</code> as:</p>\n\n<pre><code>class clName\n{\n  clName();\n  int a[10];\n};\n</code></pre>\n\n<p>We can initialize all elements in the array to its default (here all elements of array to zero) in the constructor as:</p>\n\n<pre><code>clName::clName() : a()\n{\n}\n</code></pre>\n'}, {'answer_id': 172357, 'author': 'Constantin', 'author_id': 20310, 'author_profile': 'https://Stackoverflow.com/users/20310', 'pm_score': 5, 'selected': False, 'text': "<p><code>map::operator[]</code> creates entry if key is missing and returns reference to default-constructed entry value. So you can write:</p>\n\n<pre><code>map&lt;int, string&gt; m;\nstring&amp; s = m[42]; // no need for map::find()\nif (s.empty()) { // assuming we never store empty values in m\n  s.assign(...);\n}\ncout &lt;&lt; s;\n</code></pre>\n\n<p>I'm amazed at how many C++ programmers don't know this.</p>\n"}, {'answer_id': 218306, 'author': 'Jim Hunziker', 'author_id': 6160, 'author_profile': 'https://Stackoverflow.com/users/6160', 'pm_score': 4, 'selected': False, 'text': '<p>Putting functions or variables in a nameless namespace deprecates the use of <code>static</code> to restrict them to file scope.</p>\n'}, {'answer_id': 302563, 'author': 'Ferruccio', 'author_id': 4086, 'author_profile': 'https://Stackoverflow.com/users/4086', 'pm_score': 8, 'selected': False, 'text': "<p>Most C++ programmers are familiar with the ternary operator:</p>\n\n<pre><code>x = (y &lt; 0) ? 10 : 20;\n</code></pre>\n\n<p>However, they don't realize that it can be used as an lvalue:</p>\n\n<pre><code>(a == 0 ? a : b) = 1;\n</code></pre>\n\n<p>which is shorthand for</p>\n\n<pre><code>if (a == 0)\n    a = 1;\nelse\n    b = 1;\n</code></pre>\n\n<p>Use with caution :-)</p>\n"}, {'answer_id': 304187, 'author': 'Jason Baker', 'author_id': 2147, 'author_profile': 'https://Stackoverflow.com/users/2147', 'pm_score': 4, 'selected': False, 'text': '<p>Read a file into a vector of strings:</p>\n\n<pre><code> vector&lt;string&gt; V;\n copy(istream_iterator&lt;string&gt;(cin), istream_iterator&lt;string&gt;(),\n     back_inserter(V));\n</code></pre>\n\n<p><a href="http://www.sgi.com/tech/stl/istream_iterator.html" rel="nofollow noreferrer">istream_iterator</a></p>\n'}, {'answer_id': 312426, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 7, 'selected': False, 'text': '<blockquote>\n  <p>Pointer arithmetics.</p>\n</blockquote>\n\n<p>C++ programmers prefer to avoid pointers because of the bugs that can be introduced.</p>\n\n<p>The coolest C++ I\'ve ever seen though? <a href="http://web.archive.org/web/20120110153227/http://weegen.home.xs4all.nl/eelis/analogliterals.xhtml" rel="nofollow noreferrer" title="Analog literals.">Analog literals.</a></p>\n'}, {'answer_id': 312449, 'author': 'Johannes Schaub - litb', 'author_id': 34509, 'author_profile': 'https://Stackoverflow.com/users/34509', 'pm_score': 5, 'selected': False, 'text': '<p>A quite hidden feature is that you can define variables within an if condition, and its scope will span only over the if, and its else blocks:</p>\n\n<pre><code>if(int * p = getPointer()) {\n    // do something\n}\n</code></pre>\n\n<p>Some macros use that, for example to provide some "locked" scope like this:</p>\n\n<pre><code>struct MutexLocker { \n    MutexLocker(Mutex&amp;);\n    ~MutexLocker(); \n    operator bool() const { return false; } \nprivate:\n    Mutex &amp;m;\n};\n\n#define locked(mutex) if(MutexLocker const&amp; lock = MutexLocker(mutex)) {} else \n\nvoid someCriticalPath() {\n    locked(myLocker) { /* ... */ }\n}\n</code></pre>\n\n<p>Also BOOST_FOREACH uses it under the hood. To complete this, it\'s not only possible in an if, but also in a switch:</p>\n\n<pre><code>switch(int value = getIt()) {\n    // ...\n}\n</code></pre>\n\n<p>and in a while loop:</p>\n\n<pre><code>while(SomeThing t = getSomeThing()) {\n    // ...\n}\n</code></pre>\n\n<p>(and also in a for condition). But i\'m not too sure whether these are all that useful :)</p>\n'}, {'answer_id': 409233, 'author': 'Özgür', 'author_id': 12652, 'author_profile': 'https://Stackoverflow.com/users/12652', 'pm_score': 2, 'selected': False, 'text': '<p>From <a href="http://cpptruths.blogspot.com/2008/01/function-template-overload-resolution.html" rel="nofollow noreferrer">C++ Truths</a>.</p>\n\n<p>Defining functions having identical signatures in the same scope, so this is legal:</p>\n\n<pre><code>template&lt;class T&gt; // (a) a base template\nvoid f(T) {\n  std::cout &lt;&lt; "f(T)\\n";\n}\n\ntemplate&lt;&gt;\nvoid f&lt;&gt;(int*) { // (b) an explicit specialization\n  std::cout &lt;&lt; "f(int *) specilization\\n";\n}\n\ntemplate&lt;class T&gt; // (c) another, overloads (a)\nvoid f(T*) {\n  std::cout &lt;&lt; "f(T *)\\n";\n}\n\ntemplate&lt;&gt;\nvoid f&lt;&gt;(int*) { // (d) another identical explicit specialization\n  std::cout &lt;&lt; "f(int *) another specilization\\n";\n}\n</code></pre>\n'}, {'answer_id': 421854, 'author': 'Özgür', 'author_id': 12652, 'author_profile': 'https://Stackoverflow.com/users/12652', 'pm_score': 1, 'selected': False, 'text': '<p>If operator delete() takes size argument in addition to *void, that means it will, highly, be a base class. That size argument render possible checking the size of the types in order to destroy the correct one. Here what <a href="http://semantics.org/commonknowledge/index.html" rel="nofollow noreferrer">Stephen Dewhurst</a> tells about this:</p>\n\n<blockquote>\n  <p>Notice also that we\'ve employed a\n  two-argument version of operator\n  delete rather than the usual\n  one-argument version. This\n  two-argument version is another\n  "usual" version of member operator\n  delete often employed by base classes\n  that expect derived classes to inherit\n  their operator delete implementation.\n  The second argument will contain the\n  size of the object being\n  deleted—information that is often\n  useful in implementing custom memory\n  management.</p>\n</blockquote>\n'}, {'answer_id': 421896, 'author': 'Eclipse', 'author_id': 8701, 'author_profile': 'https://Stackoverflow.com/users/8701', 'pm_score': 4, 'selected': False, 'text': '<p>One of the most interesting grammars of any programming languages.</p>\n\n<p>Three of these things belong together, and two are something altogether different...</p>\n\n<pre><code>SomeType t = u;\nSomeType t(u);\nSomeType t();\nSomeType t;\nSomeType t(SomeType(u));\n</code></pre>\n\n<p>All but the third and fifth define a <code>SomeType</code> object on the stack and initialize it (with <code>u</code> in the first two case, and the default constructor in the fourth.   The third is declaring a function that takes no parameters and returns a <code>SomeType</code>.  The fifth is similarly declaring a function that takes one parameter by value of type <code>SomeType</code> named <code>u</code>.</p>\n'}, {'answer_id': 432333, 'author': 'Johannes Schaub - litb', 'author_id': 34509, 'author_profile': 'https://Stackoverflow.com/users/34509', 'pm_score': 6, 'selected': False, 'text': "<p>One thing that's little known is that unions can be templates too:</p>\n\n<pre><code>template&lt;typename From, typename To&gt;\nunion union_cast {\n    From from;\n    To   to;\n\n    union_cast(From from)\n        :from(from) { }\n\n    To getTo() const { return to; }\n};\n</code></pre>\n\n<p>And they can have constructors and member functions too. Just nothing that has to do with inheritance (including virtual functions). </p>\n"}, {'answer_id': 456773, 'author': 'Özgür', 'author_id': 12652, 'author_profile': 'https://Stackoverflow.com/users/12652', 'pm_score': 4, 'selected': False, 'text': '<p>Defining ordinary friend functions in class templates needs special attention:</p>\n\n<pre><code>template &lt;typename T&gt; \nclass Creator { \n    friend void appear() {  // a new function ::appear(), but it doesn\'t \n        …                   // exist until Creator is instantiated \n    } \n};\nCreator&lt;void&gt; miracle;  // ::appear() is created at this point \nCreator&lt;double&gt; oops;   // ERROR: ::appear() is created a second time! \n</code></pre>\n\n<p>In this example, two different instantiations create two identical definitions—a direct violation of the <a href="http://en.wikipedia.org/wiki/One_Definition_Rule" rel="noreferrer">ODR</a> </p>\n\n<p>We must therefore make sure the template parameters of the class template appear in the type of any friend function defined in that template (unless we want to prevent more than one instantiation of a class template in a particular file, but this is rather unlikely). Let\'s apply this to a variation of our previous example:</p>\n\n<pre><code>template &lt;typename T&gt; \nclass Creator { \n    friend void feed(Creator&lt;T&gt;*){  // every T generates a different \n        …                           // function ::feed() \n    } \n}; \n\nCreator&lt;void&gt; one;     // generates ::feed(Creator&lt;void&gt;*) \nCreator&lt;double&gt; two;   // generates ::feed(Creator&lt;double&gt;*) \n</code></pre>\n\n<p>Disclaimer: I have pasted this section from <a href="https://rads.stackoverflow.com/amzn/click/com/0201734842" rel="noreferrer" rel="nofollow noreferrer">C++ Templates: The Complete Guide</a> / Section 8.4</p>\n'}, {'answer_id': 456787, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>A dangerous secret is</p>\n\n<pre><code>Fred* f = new(ram) Fred(); http://www.parashift.com/c++-faq-lite/dtors.html#faq-11.10\nf-&gt;~Fred();\n</code></pre>\n\n<p>My favorite secret I rarely see used:</p>\n\n<pre><code>class A\n{\n};\n\nstruct B\n{\n  A a;\n  operator A&amp;() { return a; }\n};\n\nvoid func(A a) { }\n\nint main()\n{\n  A a, c;\n  B b;\n  a=c;\n  func(b); //yeah baby\n  a=b; //gotta love this\n}\n</code></pre>\n'}, {'answer_id': 572900, 'author': 'dirkgently', 'author_id': 66692, 'author_profile': 'https://Stackoverflow.com/users/66692', 'pm_score': 0, 'selected': False, 'text': '<pre><code>class Empty {};\n\nnamespace std {\n  // #1 specializing from std namespace is okay under certain circumstances\n  template&lt;&gt;\n  void swap&lt;Empty&gt;(Empty&amp;, Empty&amp;) {} \n}\n\n/* #2 The following function has no arguments. \n   There is no \'unknown argument list\' as we do\n   in C.\n*/\nvoid my_function() { \n  cout &lt;&lt; "whoa! an error\\n"; // #3 using can be scoped, as it is in main below\n  // and this doesn\'t affect things outside of that scope\n}\n\nint main() {\n  using namespace std; /* #4 you can use using in function scopes */\n  cout &lt;&lt; sizeof(Empty) &lt;&lt; "\\n"; /* #5 sizeof(Empty) is never 0 */\n  /* #6 falling off of main without an explicit return means "return 0;" */\n}\n</code></pre>\n'}, {'answer_id': 674995, 'author': 'Özgür', 'author_id': 12652, 'author_profile': 'https://Stackoverflow.com/users/12652', 'pm_score': 1, 'selected': False, 'text': '<p><a href="http://www.devx.com/cplus/10MinuteSolution/32145/0/page/1" rel="nofollow noreferrer">Indirect Conversion Idiom</a>:</p>\n\n<blockquote>\n  <p>Suppose you\'re designing a smart\n  pointer class. In addition to\n  overloading the operators * and ->, a\n  smart pointer class usually defines a\n  conversion operator to bool:</p>\n</blockquote>\n\n<pre><code>template &lt;class T&gt;\nclass Ptr\n{\npublic:\n operator bool() const\n {\n  return (rawptr ? true: false);\n }\n//..more stuff\nprivate:\n T * rawptr;\n};\n</code></pre>\n\n<blockquote>\n  <p>The conversion to bool enables clients\n  to use smart pointers in expressions\n  that require bool operands:</p>\n</blockquote>\n\n<pre><code>Ptr&lt;int&gt; ptr(new int);\nif(ptr ) //calls operator bool()\n cout&lt;&lt;"int value is: "&lt;&lt;*ptr &lt;&lt;endl;\nelse\n cout&lt;&lt;"empty"&lt;&lt;endl;\n</code></pre>\n\n<blockquote>\n  <p>Furthermore, the implicit conversion\n  to bool is required in conditional\n  declarations such as:</p>\n</blockquote>\n\n<pre><code>if (shared_ptr&lt;X&gt; px = dynamic_pointer_cast&lt;X&gt;(py))\n{\n //we get here only of px isn\'t empty\n} \n</code></pre>\n\n<blockquote>\n  <p>Alas, this automatic conversion opens\n  the gate to unwelcome surprises:</p>\n</blockquote>\n\n<pre><code>Ptr &lt;int&gt; p1;\nPtr &lt;double&gt; p2;\n\n//surprise #1\ncout&lt;&lt;"p1 + p2 = "&lt;&lt; p1+p2 &lt;&lt;endl; \n//prints 0, 1, or 2, although there isn\'t an overloaded operator+()\n\nPtr &lt;File&gt; pf;\nPtr &lt;Query&gt; pq; // Query and File are unrelated \n\n//surprise #2\nif(pf==pq) //compares bool values, not pointers! \n</code></pre>\n\n<p>Solution: Use the "indirect conversion" idiom, by a conversion from pointer to data member[pMember] to bool so that there will be only 1 implicit conversion, which will prevent aforementioned unexpected behaviour: pMember->bool rather that bool->something else.</p>\n'}, {'answer_id': 691496, 'author': 'Özgür', 'author_id': 12652, 'author_profile': 'https://Stackoverflow.com/users/12652', 'pm_score': 2, 'selected': False, 'text': '<p>Pay attention to difference between free function pointer and member function pointer initializations:</p>\n\n<p>member function:</p>\n\n<pre><code>struct S\n{\n void func(){};\n};\nint main(){\nvoid (S::*pmf)()=&amp;S::func;//  &amp; is mandatory\n}\n</code></pre>\n\n<p>and free function:</p>\n\n<pre><code>void func(int){}\nint main(){\nvoid (*pf)(int)=func; // &amp; is unnecessary it can be &amp;func as well; \n}\n</code></pre>\n\n<p>Thanks to this redundant &amp;, you can add stream manipulators-which are free functions- in chain without it:</p>\n\n<pre><code>cout&lt;&lt;hex&lt;&lt;56; //otherwise you would have to write cout&lt;&lt;&amp;hex&lt;&lt;56, not neat.\n</code></pre>\n'}, {'answer_id': 730018, 'author': 'Özgür', 'author_id': 12652, 'author_profile': 'https://Stackoverflow.com/users/12652', 'pm_score': 2, 'selected': False, 'text': '<p><a href="https://stackoverflow.com/questions/257288/possible-for-c-template-to-check-for-a-functions-existence">Is it possible for C++ template to check for a function’s existence?</a></p>\n'}, {'answer_id': 754133, 'author': 'Özgür', 'author_id': 12652, 'author_profile': 'https://Stackoverflow.com/users/12652', 'pm_score': -1, 'selected': False, 'text': '<p>Emulating <strong>reinterpret cast</strong> with <strong>static cast</strong> :</p>\n\n<pre><code>int var;\nstring *str = reinterpret_cast&lt;string*&gt;(&amp;var);\n</code></pre>\n\n<p>the above code is equivalent to following:</p>\n\n<pre><code>int var;    \nstring *str = static_cast&lt;string*&gt;(static_cast&lt;void*&gt;(&amp;var));\n</code></pre>\n'}, {'answer_id': 876180, 'author': 'a_m0d', 'author_id': 106762, 'author_profile': 'https://Stackoverflow.com/users/106762', 'pm_score': 1, 'selected': False, 'text': "<p>The class and struct class-keys are nearly identical.  The main difference is that classes default to private access for members and bases, while structs default to public:</p>\n\n<pre><code>// this is completely valid C++:\nclass A;\nstruct A { virtual ~A() = 0; };\nclass B : public A { public: virtual ~B(); };\n\n// means the exact same as:\nstruct A;\nclass A { public: virtual ~A() = 0; };\nstruct B : A { virtual ~B(); };\n\n// you can't even tell the difference from other code whether 'struct'\n// or 'class' was used for A and B\n</code></pre>\n\n<p>Unions can also have members and methods, and default to public access similarly to structs.</p>\n"}, {'answer_id': 889001, 'author': 'Johannes Schaub - litb', 'author_id': 34509, 'author_profile': 'https://Stackoverflow.com/users/34509', 'pm_score': 7, 'selected': False, 'text': '<p>Not only can variables be declared in the init part of a <code>for</code> loop, but also classes and functions. </p>\n\n<pre><code>for(struct { int a; float b; } loop = { 1, 2 }; ...; ...) {\n    ...\n}\n</code></pre>\n\n<p>That allows for multiple variables of differing types.</p>\n'}, {'answer_id': 903449, 'author': 'Özgür', 'author_id': 12652, 'author_profile': 'https://Stackoverflow.com/users/12652', 'pm_score': 0, 'selected': False, 'text': '<p>Adding <a href="https://stackoverflow.com/questions/122316/template-constraints-c">constraints</a> to templates.</p>\n'}, {'answer_id': 1029069, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>Primitive types have constructors.</p>\n\n<pre><code>int i(3);\n</code></pre>\n\n<p>works.</p>\n'}, {'answer_id': 1064070, 'author': 'vobject', 'author_id': 53911, 'author_profile': 'https://Stackoverflow.com/users/53911', 'pm_score': 2, 'selected': False, 'text': '<p>It seems to me that only few people know about unnamed namespaces: </p>\n\n<pre><code>namespace {\n  // Classes, functions, and objects here.\n}\n</code></pre>\n\n<p>Unnamed namespaces behave as if they was replaced by:</p>\n\n<pre><code>namespace __unique_name__ { /* empty body */ }\nusing namespace __unique_name__;\nnamespace __unique_name__ {\n  // original namespace body\n}\n</code></pre>\n\n<p>".. where all occurances of [this unique name] in a translation unit are replaced by the same identifier and this identifier differs from all other identifiers in the entire program." [C++03, 7.3.1.1/1]</p>\n'}, {'answer_id': 1065606, 'author': 'Johannes Schaub - litb', 'author_id': 34509, 'author_profile': 'https://Stackoverflow.com/users/34509', 'pm_score': 5, 'selected': False, 'text': '<p>You can access protected data and function members of any class, without undefined behavior, and with expected semantics. Read on to see how. Read also <a href="http://tinyurl.com/defect-report" rel="nofollow noreferrer">the defect report</a> about this. </p>\n\n<p>Normally, C++ forbids you to access non-static protected members of a class\'s object, even if that class is your base class</p>\n\n<pre><code>struct A {\nprotected:\n    int a;\n};\n\nstruct B : A {\n    // error: can\'t access protected member\n    static int get(A &amp;x) { return x.a; }\n};\n\nstruct C : A { };\n</code></pre>\n\n<p>That\'s forbidden: You and the compiler don\'t know what the reference actually points at. It could be a <code>C</code> object, in which case class <code>B</code> has no business and clue about its data. Such access is only granted if <code>x</code> is a reference to a derived class or one derived from it. And it could allow arbitrary piece of code to read any protected member by just making up a "throw-away" class that reads out members, for example of <code>std::stack</code>:</p>\n\n<pre><code>void f(std::stack&lt;int&gt; &amp;s) {\n    // now, let\'s decide to mess with that stack!\n    struct pillager : std::stack&lt;int&gt; {\n        static std::deque&lt;int&gt; &amp;get(std::stack&lt;int&gt; &amp;s) {\n            // error: stack&lt;int&gt;::c is protected\n            return s.c;\n        }\n    };\n\n    // haha, now let\'s inspect the stack\'s middle elements!\n    std::deque&lt;int&gt; &amp;d = pillager::get(s);\n}\n</code></pre>\n\n<p>Surely, as you see this would cause way too much damage. But now, member pointers allow circumventing this protection! The key point is that the type of a member pointer is bound to the class that actually contains said member - <em>not</em> to the class that you specified when taking the address. This allows us to circumvent checking</p>\n\n<pre><code>struct A {\nprotected:\n    int a;\n};\n\nstruct B : A {\n    // valid: *can* access protected member\n    static int get(A &amp;x) { return x.*(&amp;B::a); }\n};\n\nstruct C : A { };\n</code></pre>\n\n<p>And of course, it also works with the <code>std::stack</code> example. </p>\n\n<pre><code>void f(std::stack&lt;int&gt; &amp;s) {\n    // now, let\'s decide to mess with that stack!\n    struct pillager : std::stack&lt;int&gt; {\n        static std::deque&lt;int&gt; &amp;get(std::stack&lt;int&gt; &amp;s) {\n            return s.*(pillager::c);\n        }\n    };\n\n    // haha, now let\'s inspect the stack\'s middle elements!\n    std::deque&lt;int&gt; &amp;d = pillager::get(s);\n}\n</code></pre>\n\n<p>That\'s going to be even easier with a using declaration in the derived class, which makes the member name public and refers to the member of the base class. </p>\n\n<pre><code>void f(std::stack&lt;int&gt; &amp;s) {\n    // now, let\'s decide to mess with that stack!\n    struct pillager : std::stack&lt;int&gt; {\n        using std::stack&lt;int&gt;::c;\n    };\n\n    // haha, now let\'s inspect the stack\'s middle elements!\n    std::deque&lt;int&gt; &amp;d = s.*(&amp;pillager::c);\n}\n</code></pre>\n'}, {'answer_id': 1402670, 'author': 'Kamil Szot', 'author_id': 166921, 'author_profile': 'https://Stackoverflow.com/users/166921', 'pm_score': 0, 'selected': False, 'text': '<p>Member pointers and member pointer operator ->* </p>\n\n<pre><code>#include &lt;stdio.h&gt;\nstruct A { int d; int e() { return d; } };\nint main() {\n    A* a = new A();\n    a-&gt;d = 8;\n    printf("%d %d\\n", a -&gt;* &amp;A::d, (a -&gt;* &amp;A::e)() );\n    return 0;\n}\n</code></pre>\n\n<p>For methods (a ->* &amp;A::e)() is a bit like Function.call() from javascript </p>\n\n<pre><code>var f = A.e\nf.call(a) \n</code></pre>\n\n<p>For members it\'s a bit like accessing with [] operator </p>\n\n<pre><code>a[\'d\']\n</code></pre>\n'}, {'answer_id': 1414869, 'author': 'Johannes Schaub - litb', 'author_id': 34509, 'author_profile': 'https://Stackoverflow.com/users/34509', 'pm_score': 5, 'selected': False, 'text': '<p>Many know of the <code>identity</code> / <code>id</code> metafunction, but there is a nice usecase for it for non-template cases: Ease writing declarations:</p>\n\n<pre><code>// void (*f)(); // same\nid&lt;void()&gt;::type *f;\n\n// void (*f(void(*p)()))(int); // same\nid&lt;void(int)&gt;::type *f(id&lt;void()&gt;::type *p);\n\n// int (*p)[2] = new int[10][2]; // same\nid&lt;int[2]&gt;::type *p = new int[10][2];\n\n// void (C::*p)(int) = 0; // same\nid&lt;void(int)&gt;::type C::*p = 0;\n</code></pre>\n\n<p>It helps decrypting C++ declarations greatly!</p>\n\n<pre><code>// boost::identity is pretty much the same\ntemplate&lt;typename T&gt; \nstruct id { typedef T type; };\n</code></pre>\n'}, {'answer_id': 1465581, 'author': 'sdcvvc', 'author_id': 100020, 'author_profile': 'https://Stackoverflow.com/users/100020', 'pm_score': 2, 'selected': False, 'text': '<p><a href="http://www.reddit.com/r/programming/comments/96aku/in_c_throw_is_an_expression/" rel="nofollow noreferrer">throw is an expression</a></p>\n'}, {'answer_id': 1573354, 'author': 'Macke', 'author_id': 72312, 'author_profile': 'https://Stackoverflow.com/users/72312', 'pm_score': 1, 'selected': False, 'text': "<p>I find recursive template instatiations pretty cool:</p>\n\n<pre><code>template&lt;class int&gt;\nclass foo;\n\ntemplate\nclass foo&lt;0&gt; {\n    int* get&lt;0&gt;() { return array; }\n    int* array;  \n};\n\ntemplate&lt;class int&gt;\nclass foo&lt;i&gt; : public foo&lt;i-1&gt; {\n    int* get&lt;i&gt;() { return array + 1; }  \n};\n</code></pre>\n\n<p>I've used that to generate a class with 10-15 functions that return pointers into various parts of an array, since an API I used required one function pointer for each value.</p>\n\n<p>I.e. programming the compiler to generate a bunch of functions, via recursion. Easy as pie. :)</p>\n"}, {'answer_id': 1771776, 'author': 'Jeffrey Faust', 'author_id': 215580, 'author_profile': 'https://Stackoverflow.com/users/215580', 'pm_score': 2, 'selected': False, 'text': '<p>main() does not need a return value:</p>\n\n<pre><code>int main(){}\n</code></pre>\n\n<p>is the shortest valid C++ program.</p>\n'}, {'answer_id': 1771843, 'author': 'Kaz Dragon', 'author_id': 24913, 'author_profile': 'https://Stackoverflow.com/users/24913', 'pm_score': 4, 'selected': False, 'text': '<p>You can template bitfields.</p>\n\n<pre><code>template &lt;size_t X, size_t Y&gt;\nstruct bitfield\n{\n    char left  : X;\n    char right : Y;\n};\n</code></pre>\n\n<p>I have yet to come up with any purpose for this, but it sure as heck surprised me.</p>\n'}, {'answer_id': 1966865, 'author': 'Rune FS', 'author_id': 112407, 'author_profile': 'https://Stackoverflow.com/users/112407', 'pm_score': 0, 'selected': False, 'text': "<p>My favorite (for the time being) is the lack of sematics in a statement like \nA=B=C. What the value of A is basically undetermined.</p>\n\n<p>Think of this:</p>\n\n<pre><code>class clC\n{\npublic:\n   clC&amp; operator=(const clC&amp; other)\n   {\n      //do some assignment stuff\n      return copy(other);\n   }\n   virtual clC&amp; copy(const clC&amp; other);\n}\n\nclass clB : public clC\n{\npublic:\n  clB() : m_copy()\n  {\n  }\n\n  clC&amp; copy(const clC&amp; other)\n  {\n    return m_copy;\n  }\n\nprivate:\n  class clInnerB : public clC\n  {\n  }\n  clInnerB m_copy;\n}\n</code></pre>\n\n<p>now A might be of a type inaccessible to any other than objects of type clB and have a value that's unrelated to C.</p>\n"}, {'answer_id': 2176229, 'author': 'Johannes Schaub - litb', 'author_id': 34509, 'author_profile': 'https://Stackoverflow.com/users/34509', 'pm_score': 4, 'selected': False, 'text': '<h3>void functions can return void values</h3>\n\n<p>Little known, but the following code is fine</p>\n\n<pre><code>void f() { }\nvoid g() { return f(); }\n</code></pre>\n\n<p>Aswell as the following weird looking one</p>\n\n<pre><code>void f() { return (void)"i\'m discarded"; }\n</code></pre>\n\n<p>Knowing about this, you can take advantage in some areas. One example: <code>void</code> functions can\'t return a value but you can also not just return nothing, because they may be instantiated with non-void. Instead of storing the value into a local variable, which will cause an error for <code>void</code>, just return a value directly</p>\n\n<pre><code>template&lt;typename T&gt;\nstruct sample {\n  // assume f&lt;T&gt; may return void\n  T dosomething() { return f&lt;T&gt;(); }\n\n  // better than T t = f&lt;T&gt;(); /* ... */ return t; !\n};\n</code></pre>\n'}, {'answer_id': 2176258, 'author': 'Johannes Schaub - litb', 'author_id': 34509, 'author_profile': 'https://Stackoverflow.com/users/34509', 'pm_score': 5, 'selected': False, 'text': "<h3>Preventing comma operator from calling operator overloads</h3>\n\n<p>Sometimes you make valid use of the comma operator, but you want to ensure that no user defined comma operator gets into the way, because for instance you rely on sequence points between the left and right side or want to make sure nothing interferes with the desired action. This is where <code>void()</code> comes into game:</p>\n\n<pre><code>for(T i, j; can_continue(i, j); ++i, void(), ++j)\n  do_code(i, j);\n</code></pre>\n\n<p>Ignore the place holders i put for the condition and code. What's important is the <code>void()</code>, which makes the compiler force to use the builtin comma operator. This can be useful when implementing traits classes, sometimes, too. </p>\n"}, {'answer_id': 2339965, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>You can view all the predefined macros through command-line switches with some compilers.  This works with gcc and icc (Intel\'s C++ compiler):</p>\n\n<pre><code>$ touch empty.cpp\n$ g++ -E -dM empty.cpp | sort &gt;gxx-macros.txt\n$ icc -E -dM empty.cpp | sort &gt;icx-macros.txt\n$ touch empty.c\n$ gcc -E -dM empty.c | sort &gt;gcc-macros.txt\n$ icc -E -dM empty.c | sort &gt;icc-macros.txt\n</code></pre>\n\n<p>For MSVC they are listed in a <a href="http://msdn.microsoft.com/en-us/library/b0084kay%28VS.80%29.aspx" rel="nofollow noreferrer">single place</a>.  They could be documented in a single place for the others too, but with the above commands you can clearly <em>see</em> what is and isn\'t defined and exactly what values are used, after applying all of the other command-line switches.</p>\n\n<p>Compare (after sorting):</p>\n\n<pre><code> $ diff gxx-macros.txt icx-macros.txt\n $ diff gxx-macros.txt gcc-macros.txt\n $ diff icx-macros.txt icc-macros.txt\n</code></pre>\n'}, {'answer_id': 2339999, 'author': 'AnT stands with Russia', 'author_id': 187690, 'author_profile': 'https://Stackoverflow.com/users/187690', 'pm_score': 4, 'selected': False, 'text': '<p>The ternary conditional operator <code>?:</code> requires its second and third operand to have "agreeable" types (speaking informally). But this requirement has one exception (pun intended): either the second or third operand can be a throw expression (which has type <code>void</code>), regardless of the type of the other operand.</p>\n\n<p>In other words, one can write the following pefrectly valid C++ expressions using the <code>?:</code> operator</p>\n\n<pre><code>i = a &gt; b ? a : throw something();\n</code></pre>\n\n<p>BTW, the fact that throw expression is actually <em>an expression</em> (of type <code>void</code>) and not a statement is another little-known feature of C++ language. This means, among other things, that the following code is perfectly valid</p>\n\n<pre><code>void foo()\n{\n  return throw something();\n}\n</code></pre>\n\n<p>although there\'s not much point in doing it this way (maybe in some generic template code this might come handy).</p>\n'}, {'answer_id': 2340305, 'author': 'Viktor Sehr', 'author_id': 100724, 'author_profile': 'https://Stackoverflow.com/users/100724', 'pm_score': 2, 'selected': False, 'text': "<ol>\n<li><p><code>map::insert(std::pair(key, value));</code> doesn't overwrite if key value already exists.  </p></li>\n<li><p>You can instantiate a class right after its definition:\n(I might add that this feature has given me hundreds of compilation errors because of the missing semicolon, and I've never ever seen anyone use this on classes)</p>\n\n<pre><code>class MyClass {public: /* code */} myClass;\n</code></pre></li>\n</ol>\n"}, {'answer_id': 2340449, 'author': 'aheld', 'author_id': 259873, 'author_profile': 'https://Stackoverflow.com/users/259873', 'pm_score': -1, 'selected': False, 'text': '<p>I know somebody who defines a getter and a setter at the same time with only one method. Like this:</p>\n\n<pre><code>class foo\n{\n    int x;\n\n    int* GetX(){\n        return &amp;x;\n    }\n}\n</code></pre>\n\n<p>You can now use this as a getter as usual (well, almost):</p>\n\n<pre><code>int a = *GetX();\n</code></pre>\n\n<p>and as a setter:</p>\n\n<pre><code>*GetX() = 17;\n</code></pre>\n'}, {'answer_id': 2520439, 'author': 'osgx', 'author_id': 196561, 'author_profile': 'https://Stackoverflow.com/users/196561', 'pm_score': -1, 'selected': False, 'text': '<p>Template metaprogramming is.</p>\n'}, {'answer_id': 2912402, 'author': 'mihai', 'author_id': 350838, 'author_profile': 'https://Stackoverflow.com/users/350838', 'pm_score': -1, 'selected': False, 'text': '<p>Not actually a hidden feature, but pure awesomeness:</p>\n\n<pre><code>#define private public \n</code></pre>\n'}, {'answer_id': 3056080, 'author': 'Martín Fixman', 'author_id': 305597, 'author_profile': 'https://Stackoverflow.com/users/305597', 'pm_score': -1, 'selected': False, 'text': '<p>You can return a variable reference as part of a function. It has some uses, mostly for producing horrible code:</p>\n\n<pre><code>int s ;\nvector &lt;int&gt; a ;\nvector &lt;int&gt; b ;\n\nint &amp;G(int h)\n{\n    if ( h &lt; a.size() ) return a[h] ;\n    if ( h - a.size() &lt; b.size() ) return b[ h - a.size() ] ;\n    return s ;\n}\n\nint main()\n{\n    a = vector &lt;int&gt; (100) ;\n    b = vector &lt;int&gt; (100) ;\n\n    G( 20) = 40 ; //a[20] becomes 40\n    G(120) = 40 ; //b[20] becomes 40\n    G(424) = 40 ; //s becomes 40\n}\n</code></pre>\n'}, {'answer_id': 3100801, 'author': 'Alexandre C.', 'author_id': 373025, 'author_profile': 'https://Stackoverflow.com/users/373025', 'pm_score': 3, 'selected': False, 'text': "<p>Local classes are awesome :</p>\n\n<pre><code>struct MyAwesomeAbstractClass\n{ ... };\n\n\ntemplate &lt;typename T&gt;\nMyAwesomeAbstractClass*\ncreate_awesome(T param)\n{\n    struct ans : MyAwesomeAbstractClass\n    {\n        // Make the implementation depend on T\n    };\n\n    return new ans(...);\n}\n</code></pre>\n\n<p>quite neat, since it doesn't pollute the namespace with useless class definitions...</p>\n"}, {'answer_id': 3176148, 'author': 'Johannes Schaub - litb', 'author_id': 34509, 'author_profile': 'https://Stackoverflow.com/users/34509', 'pm_score': 3, 'selected': False, 'text': '<p>One hidden feature, even hidden to the <a href="http://gcc.gnu.org/bugzilla/show_bug.cgi?id=43453" rel="nofollow noreferrer">GCC developers</a>, is to initialize an array member using a string literal. Suppose you have a structure that needs to work with a C array, and you want to initialize the array member with a default content</p>\n\n<pre><code>struct Person {\n  char name[255];\n  Person():name("???") { }\n};\n</code></pre>\n\n<p>This works, and only works with char arrays and string literal initializers. No <code>strcpy</code> is needed!</p>\n'}, {'answer_id': 3176186, 'author': 'Johannes Schaub - litb', 'author_id': 34509, 'author_profile': 'https://Stackoverflow.com/users/34509', 'pm_score': 5, 'selected': False, 'text': '<p>Another hidden feature is that you can call class objects that can be converted to function pointers or references. Overload resolution is done on the result of them, and arguments are perfectly forwarded.</p>\n\n<pre><code>template&lt;typename Func1, typename Func2&gt;\nclass callable {\n  Func1 *m_f1;\n  Func2 *m_f2;\n\npublic:\n  callable(Func1 *f1, Func2 *f2):m_f1(f1), m_f2(f2) { }\n  operator Func1*() { return m_f1; }\n  operator Func2*() { return m_f2; }\n};\n\nvoid foo(int i) { std::cout &lt;&lt; "foo: " &lt;&lt; i &lt;&lt; std::endl; }\nvoid bar(long il) { std::cout &lt;&lt; "bar: " &lt;&lt; il &lt;&lt; std::endl; }\n\nint main() {\n  callable&lt;void(int), void(long)&gt; c(foo, bar);\n  c(42); // calls foo\n  c(42L); // calls bar\n}\n</code></pre>\n\n<p>These are called "surrogate call functions". </p>\n'}, {'answer_id': 3182557, 'author': 'Johannes Schaub - litb', 'author_id': 34509, 'author_profile': 'https://Stackoverflow.com/users/34509', 'pm_score': 6, 'selected': False, 'text': '<p>Another hidden feature that doesn\'t work in C is the functionality of the unary <code>+</code> operator. You can use it to promote and decay all sorts of things</p>\n\n<h3>Converting an Enumeration to an integer</h3>\n\n<pre><code>+AnEnumeratorValue\n</code></pre>\n\n<p>And your enumerator value that previously had its enumeration type now has the perfect integer type that can fit its value. Manually, you would hardly know that type! This is needed for example when you want to implement an overloaded operator for your enumeration. </p>\n\n<h3>Get the value out of a variable</h3>\n\n<p>You have to use a class that uses an in-class static initializer without an out of class definition, but sometimes it fails to link? The operator may help to create a temporary without making assumptins or dependencies on its type</p>\n\n<pre><code>struct Foo {\n  static int const value = 42;\n};\n\n// This does something interesting...\ntemplate&lt;typename T&gt;\nvoid f(T const&amp;);\n\nint main() {\n  // fails to link - tries to get the address of "Foo::value"!\n  f(Foo::value);\n\n  // works - pass a temporary value\n  f(+Foo::value);\n}\n</code></pre>\n\n<h3>Decay an array to a pointer</h3>\n\n<p>Do you want to pass two pointers to a function, but it just won\'t work? The operator may help</p>\n\n<pre><code>// This does something interesting...\ntemplate&lt;typename T&gt;\nvoid f(T const&amp; a, T const&amp; b);\n\nint main() {\n  int a[2];\n  int b[3];\n  f(a, b); // won\'t work! different values for "T"!\n  f(+a, +b); // works! T is "int*" both time\n}\n</code></pre>\n'}, {'answer_id': 3189052, 'author': 'Johannes Schaub - litb', 'author_id': 34509, 'author_profile': 'https://Stackoverflow.com/users/34509', 'pm_score': 4, 'selected': False, 'text': '<p>The dominance rule is useful, but little known. It says that even if in a non-unique path through a base-class lattice, name-lookup for a partially hidden member is unique if the member belongs to a virtual base-class:</p>\n\n<pre><code>struct A { void f() { } };\n\nstruct B : virtual A { void f() { cout &lt;&lt; "B!"; } };\nstruct C : virtual A { };\n\n// name-lookup sees B::f and A::f, but B::f dominates over A::f !\nstruct D : B, C { void g() { f(); } };\n</code></pre>\n\n<p>I\'ve used this to <a href="https://stackoverflow.com/questions/2366879/operator-new-overloading-and-alignment/2366998#2366998">implement alignment-support</a> that automatically figures out the strictest alignment by means of the dominance rule. </p>\n\n<p><em>This does not only apply to virtual functions, but also to typedef names, static/non-virtual members and anything else.</em> I\'ve seen it used to implement overwritable traits in meta-programs. </p>\n'}]
['https://Stackoverflow.com/questions/75538', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2328/']