Derived classes

Any class type (whether declared with class-key class or struct ) may be declared as derived from one or more base classes which, in turn, may be derived from their own base classes, forming an inheritance hierarchy.

Contents

[edit] Syntax

The list of base classes is provided in the base-clause of the class declaration syntax. The base-clause consists of the character : followed by a comma-separated list of one or more base-specifier s.

attr  (optional) class-or-computed (1)
attr  (optional) virtual class-or-computed (2)
attr  (optional) access-specifier class-or-computed (3)
attr  (optional) virtual access-specifier class-or-computed (4)
attr  (optional) access-specifier virtual class-or-computed (5)
1) Specifies a non-virtual inheritance with default member accessibility. 2) Specifies a virtual inheritance with default member accessibility. 3) Specifies a non-virtual inheritance with given member accessibility. 4) Specifies a virtual inheritance with given member accessibility. 5) Same as 4), virtual and access-specifier can appear in any order.

An elaborated type specifier cannot directly appear as class-or-computed due to syntax limitations.

base-specifier s in a base-clause may be pack expansions.

A class or struct declared final cannot be denoted by class-or-computed .

If access-specifier is omitted, it defaults to public for derived classes declared with class-key struct and to private for derived classes declared with class-key class .

struct Base { int a, b, c; }; // every object of type Derived includes Base as a subobject struct Derived : Base { int b; }; // every object of type Derived2 includes Derived and Base as subobjects struct Derived2 : Derived { int c; };

Classes denoted by class-or-computed 's listed in the base-clause are direct base classes. Their bases are indirect base classes. The same class cannot be specified as a direct base class more than once, but the same class can be both direct and indirect base class.

Each direct and indirect base class is present, as base class subobject, within the object representation of the derived class at an ABI-dependent offset. Empty base classes usually do not increase the size of the derived object due to empty base optimization. The constructors of base class subobjects are called by the constructor of the derived class: arguments may be provided to those constructors in the member initializer list.

[edit] Virtual base classes

For each distinct base class that is specified virtual , the most derived object contains only one base class subobject of that type, even if the class appears many times in the inheritance hierarchy (as long as it is inherited virtual every time).

struct B { int n; }; class X : public virtual B {}; class Y : virtual public B {}; class Z : public B {}; // every object of type AA has one X, one Y, one Z, and two B's: // one that is the base of Z and one that is shared by X and Y struct AA : X, Y, Z { AA() { X::n = 1; // modifies the virtual B subobject's member Y::n = 2; // modifies the same virtual B subobject's member Z::n = 3; // modifies the non-virtual B subobject's member std::cout  X::n  Y::n  Z::n  '\n'; // prints 223 } };

An example of an inheritance hierarchy with virtual base classes is the iostreams hierarchy of the standard library: std::istream and std::ostream are derived from std::ios using virtual inheritance. std::iostream is derived from both std::istream and std::ostream , so every instance of std::iostream contains a std::ostream subobject, a std::istream subobject, and just one std::ios subobject (and, consequently, one std::ios_base ).

All virtual base subobjects are initialized before any non-virtual base subobject, so only the most derived class calls the constructors of the virtual bases in its member initializer list:

struct B { int n; B(int x) : n(x) {} }; struct X : virtual B { X() : B(1) {} }; struct Y : virtual B { Y() : B(2) {} }; struct AA : X, Y { AA() : B(3), X(), Y() {} }; // the default constructor of AA calls the default constructors of X and Y // but those constructors do not call the constructor of B because B is a virtual base AA a; // a.n == 3 // the default constructor of X calls the constructor of B X x; // x.n == 1

There are special rules for unqualified name lookup for class members when virtual inheritance is involved (sometimes referred to as the rules of dominance).

[edit] Public inheritance

When a class uses public member access specifier to derive from a base, all public members of the base class are accessible as public members of the derived class and all protected members of the base class are accessible as protected members of the derived class (private members of the base are never accessible unless friended).

Public inheritance models the subtyping relationship of object-oriented programming: the derived class object IS-A base class object. References and pointers to a derived object are expected to be usable by any code that expects references or pointers to any of its public bases (see LSP) or, in DbC terms, a derived class should maintain class invariants of its public bases, should not strengthen any precondition or weaken any postcondition of a member function it overrides.

Run this code
#include #include #include struct MenuOption { std::string title; }; // Menu is a vector of MenuOption: options can be inserted, removed, reordered. // and has a title. class Menu : public std::vectorMenuOption> { public: std::string title; void print() const { std::cout   <<span >":<span >\n</span>"</span><span >;</span> <span >for</span> <span >(</span><span >std::<span >size_t</span></span> i <span >=</span> <span >0</span>, s <span >=</span> size<span >(</span><span >)</span><span >;</span> i <span > s<span >;</span> <span >++</span>i<span >)</span> <span >std::<span >cout</span></span> <span > <<span >" "</span> <span > <<span >(</span>i <span >+</span> <span >1</span><span >)</span> <span > <<span >". "</span> <span > <at<span >(</span>i<span >)</span>.<span >title</span> <span > <<span >'<span >\n</span>'</span><span >;</span> <span >}</span> <span >}</span><span >;</span> <span >// Note: Menu::title is not problematic because its role is independent of the base class.</span> <span >enum</span> <span >class</span> Color <span >{</span> WHITE, RED, BLUE, GREEN <span >}</span><span >;</span> <span >void</span> apply_terminal_color<span >(</span>Color<span >)</span> <span >{</span> <span >/* OS-specific */</span> <span >}</span> <span >// THIS IS BAD!</span> <span >// ColorMenu is a Menu where every option has a custom color.</span> <span >class</span> ColorMenu <span >:</span> <span >public</span> Menu <span >{</span> <span >public</span><span >:</span> <span >std::<span >vector</span></span><span >Color<span >></span> colors<span >;</span> <span >void</span> print<span >(</span><span >)</span> <span >const</span> <span >{</span> <span >std::<span >cout</span></span> <span > <title <span > <<span >":<span >\n</span>"</span><span >;</span> <span >for</span> <span >(</span><span >std::<span >size_t</span></span> i <span >=</span> <span >0</span>, s <span >=</span> size<span >(</span><span >)</span><span >;</span> i <span > s<span >;</span> <span >++</span>i<span >)</span> <span >{</span> <span >std::<span >cout</span></span> <span > <<span >" "</span> <span > <<span >(</span>i <span >+</span> <span >1</span><span >)</span> <span > <<span >". "</span><span >;</span> apply_terminal_color<span >(</span>colors<span >[</span>i<span >]</span><span >)</span><span >;</span> <span >std::<span >cout</span></span> <span > <at<span >(</span>i<span >)</span>.<span >title</span> <span > <<span >'<span >\n</span>'</span><span >;</span> apply_terminal_color<span >(</span>Color<span >::</span><span >WHITE</span><span >)</span><span >;</span> <span >}</span> <span >}</span> <span >}</span><span >;</span> <span >// ColorMenu needs the following invariants that cannot be satisfied</span> <span >// by publicly inheriting from Menu, for example:</span> <span >// - ColorMenu::colors and Menu must have the same number of elements</span> <span >// - To make sense, calling erase() should remove also elements from colors,</span> <span >// in order to let options keep their colors</span> <span >// Basically every non-const call to a std::vector method will break the invariant</span> <span >// of the ColorMenu and will need fixing from the user by correctly managing colors.</span> <span >int</span> main<span >(</span><span >)</span> <span >{</span> ColorMenu color_menu<span >;</span> <span >// The big problem of this class is that we must keep ColorMenu::Color</span> <span >// in sync with Menu.</span> color_menu.<span >push_back</span><span >(</span>MenuOption<span >{</span><span >"Some choice"</span><span >}</span><span >)</span><span >;</span> <span >// color_menu.print(); // ERROR! colors[i] in print() is out of range</span> color_menu.<span >colors</span>.<span >push_back</span><span >(</span>Color<span >::</span><span >RED</span><span >)</span><span >;</span> color_menu.<span >print</span><span >(</span><span >)</span><span >;</span> <span >// OK: colors and Menu has the same number of elements</span> <span >}</span></pre>
<h3>[edit] Protected inheritance</h3>
<p>When a class uses protected member access specifier to <a href="/533592.html">derive from a</a> base, all public and protected members of the base class are accessible as protected members of <a href="/155027.html">the derived class</a> (private members of the base are never accessible unless friended).</p>
<p>Protected inheritance may be used for "controlled polymorphism": within the members of Derived, as well as within the members of all further-derived classes, <a href="/155027.html">the derived class</a> IS-A base: references and pointers to Derived may be used where references and pointers to Base are expected.</p>
<h3>[edit] Private inheritance</h3>
<p>When a class uses private member access specifier to <a href="/533592.html">derive from a</a> base, all public and protected members of the base class are accessible as private members of <a href="/155027.html">the derived class</a> (private members of the base are never accessible unless friended).</p>
<p>Private inheritance is commonly used in policy-based design, since policies are usually empty classes, and using them as bases both enables static polymorphism and leverages empty-base optimization.</p>
<p>Private inheritance can also be used to implement the composition relationship (the base class subobject is an implementation detail of <a href="/155027.html">the derived class</a> object). Using a member offers better encapsulation and is generally preferred unless <a href="/155027.html">the derived class</a> requires access to protected members (including constructors) of the base, needs to override a virtual member of the base, needs the base to be constructed before and destructed after some other base subobject, needs to share a virtual base or needs to control the construction of a virtual base. Use of members to implement composition is also not applicable in the case of multiple inheritance from a parameter pack or when the identities of the base classes are determined at compile time through template metaprogramming.</p>
<p>Similar to protected inheritance, private inheritance may also be used for controlled polymorphism: within the members of the derived (but not within further-derived classes), derived IS-A base.</p>
<pre><span >template</span><span ><span >typename</span> Transport<span >></span> <span >class</span> service <span >:</span> <span >private</span> Transport <span >// private inheritance from the Transport policy</span> <span >{</span> <span >public</span><span >:</span> <span >void</span> transmit<span >(</span><span >)</span> <span >{</span> this<span >-</span><span >></span>send<span >(</span>. <span >)</span><span >;</span> <span >// send using whatever transport was supplied</span> <span >}</span> <span >}</span><span >;</span> <span >// TCP transport policy</span> <span >class</span> tcp <span >{</span> <span >public</span><span >:</span> <span >void</span> send<span >(</span>. <span >)</span><span >;</span> <span >}</span><span >;</span> <span >// UDP transport policy</span> <span >class</span> udp <span >{</span> <span >public</span><span >:</span> <span >void</span> send<span >(</span>. <span >)</span><span >;</span> <span >}</span><span >;</span> service<span >tcp<span >></span> service<span >(</span>host, port<span >)</span><span >;</span> service.<span >transmit</span><span >(</span>. <span >)</span><span >;</span> <span >// send over TCP</span></pre>
<h3>[edit] Member name lookup</h3>
<p>Unqualified and qualified name lookup rules for class members are detailed in name lookup.</p>
<h3>[edit] Keywords</h3>
<h3>[edit] Defect reports</h3>
<p>The following behavior-changing defect reports were applied retroactively to previously published C++ standards.</p>
<table style="font-size:0.8em"> <tr><th>DR</th> <th>Applied to</th> <th>Behavior as published</th> <th>Correct behavior</th> </tr> <tr><td>CWG 1710 </td> <td>C++98</td> <td>the syntax of class-or-decltype made it impossible to derive from<br />a dependent class where the template disambiguator is required</td> <td>allowed template</td> </tr></table>
<h3>[edit] See also</h3>
<ul>
  <li>virtual functions</li>
  <li>abstract classes</li>
</ul>

  <a href="https://www.liveinternet.ru/click;denoiudenoiu"
target="_blank"><img id="licntA014" width="31" height="31" style="border:0" 
title="LiveInternet"
src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAEALAAAAAABAAEAAAIBTAA7"
alt=""/></a><script>(function(d,s){d.getElementById("licntA014").src=
"https://counter.yadro.ru/hit;denoiudenoiu?t44.6;r"+escape(d.referrer)+
((typeof(s)=="undefined")?"":";s"+s.width+"*"+s.height+"*"+
(s.colorDepth?s.colorDepth:s.pixelDepth))+";u"+escape(d.URL)+
";h"+escape(d.title.substring(0,150))+";"+Math.random()})
(document,screen)</script>
</body>
</html>