Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In C++, the only difference between a struct and a class is that struct members are public by default, and class members are private by default.</p> <p><em>However</em>, as a matter of style, it's best to use the <code>struct</code> keyword for something that could reasonably be a struct in C (more or less POD types), and the <code>class</code> keyword if it uses C++-specific features such as inheritance and member functions.</p> <p>C does not have classes.</p> <p>C structs cannot use C++-specific features.</p> <p><strong>EDIT</strong>:</p> <p>The <a href="http://www.parashift.com/c++-faq-lite/">C++ FAQ Lite</a>, question 7.9, has this to say:</p> <blockquote> <p>The members and base classes of a <code>struct</code> are <code>public</code> by default, while in <code>class</code>, they default to <code>private</code>. Note: you should make your base classes <em>explicitly</em> <code>public</code>, <code>private</code>, or <code>protected</code>, rather than relying on the defaults.</p> <p><code>struct</code> and <code>class</code> are otherwise functionally equivalent.</p> <p>OK, enough of that squeaky clean techno talk. Emotionally, most developers make a strong distinction between a <code>class</code> and a <code>struct</code>. A <code>struct</code> simply <em>feels</em> like an open pile of bits with very little in the way of encapsulation or functionality. A <code>class</code> <em>feels</em> like a living and responsible member of society with intelligent services, a strong encapsulation barrier, and a well defined interface. Since that's the connotation most people already have, you should probably use the <code>struct</code> keyword if you have a class that has very few methods and has <code>public</code> data (such things <em>do</em> exist in well designed systems!), but otherwise you should probably use the <code>class</code> keyword.</p> </blockquote> <p>And quoting Stroustrup's "The C++ Programming Language", 4th edition, section 16.2.4:</p> <blockquote> <p>These two definitions of <strong>S</strong> are interchangeable, though it is usually wise to stick to one style. Which style you use depends on circumstances and taste. I tend to use <strong>struct</strong> for classes that I think of as "just simple data structures." If I think of a class as "a proper type with an invariant," I use <strong>class</strong>. Constructors and access functions can be quite useful even for *<em>struct</em>*s, but as a shorthand rather than guarantors of invariants.</p> </blockquote>
 

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