Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Note after answer acceptance: <em>This is NOT a complete answer. Read other answers like <a href="https://stackoverflow.com/questions/656224/when-should-i-use-c-private-inheritance/656235#656235">here</a> (conceptually) and <strong><a href="https://stackoverflow.com/questions/656224/when-should-i-use-c-private-inheritance/675451#675451">here</a></strong> (both theoretic and practic) if you are interested in the question. This is just a fancy trick that can be achieved with private inheritance. While it is</em> fancy <em>it is not the answer to the question.</em></p> <p>Besides the basic usage of just private inheritance shown in the C++ FAQ (linked in other's comments) you can use a combination of private and virtual inheritance to <em>seal</em> a class (in .NET terminology) or to make a class <em>final</em> (in Java terminology). This is not a common use, but anyway I found it interesting:</p> <pre><code>class ClassSealer { private: friend class Sealed; ClassSealer() {} }; class Sealed : private virtual ClassSealer { // ... }; class FailsToDerive : public Sealed { // Cannot be instantiated }; </code></pre> <p><em>Sealed</em> can be instantiated. It derives from <em>ClassSealer</em> and can call the private constructor directly as it is a friend.</p> <p><em>FailsToDerive</em> won't compile as it must call the <em>ClassSealer</em> constructor directly (virtual inheritance requirement), but it cannot as it is private in the <em>Sealed</em> class and in this case <em>FailsToDerive</em> is not a friend of <em>ClassSealer</em>.</p> <hr> <p><strong>EDIT</strong></p> <p>It was mentioned in the comments that this could not be made generic at the time using CRTP. The C++11 standard removes that limitation by providing a different syntax to befriend template arguments:</p> <pre><code>template &lt;typename T&gt; class Seal { friend T; // not: friend class T!!! Seal() {} }; class Sealed : private virtual Seal&lt;Sealed&gt; // ... </code></pre> <p>Of course this is all moot, since C++11 provides a <code>final</code> contextual keyword for exactly this purpose:</p> <pre><code>class Sealed final // ... </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. 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