<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Where&#039;s Walden? &#187; final</title>
	<atom:link href="http://whereswalden.com/tag/final/feed/" rel="self" type="application/rss+xml" />
	<link>http://whereswalden.com</link>
	<description>Mozilla, politics, economics, law, backpacking, cycling, and other random desiderata</description>
	<lastBuildDate>Tue, 30 Apr 2013 15:17:04 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Introducing MOZ_FINAL: prevent inheriting from a class, or prevent overriding a virtual function</title>
		<link>http://whereswalden.com/2011/11/26/introducing-moz_final-prevent-inheriting-from-a-class-or-prevent-overriding-a-virtual-function/</link>
		<comments>http://whereswalden.com/2011/11/26/introducing-moz_final-prevent-inheriting-from-a-class-or-prevent-overriding-a-virtual-function/#comments</comments>
		<pubDate>Sat, 26 Nov 2011 17:17:39 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[c++11]]></category>
		<category><![CDATA[c++98]]></category>
		<category><![CDATA[final]]></category>
		<category><![CDATA[mfbt]]></category>
		<category><![CDATA[mozilla]]></category>
		<category><![CDATA[moz_final]]></category>
		<category><![CDATA[sealed]]></category>

		<guid isPermaLink="false">http://whereswalden.com/?p=3533</guid>
		<description><![CDATA[The inexorable march of progress continues in the Mozilla Framework Based on Templates with the addition of MOZ_FINAL, through which you can limit various forms of inheritance in C++. Traditional C++ inheritance mostly can&#8217;t be controlled In C++98 any class can be inherited. (An extremely obscure pattern will prevent this, but it has down sides.) [...]]]></description>
				<content:encoded><![CDATA[<p>The inexorable march of progress continues in the Mozilla Framework Based on Templates with the addition of <code>MOZ_FINAL</code>, through which you can limit various forms of inheritance in C++.</p>
<h2>Traditional C++ inheritance mostly can&#8217;t be controlled</h2>
<p>In C++98 any class can be inherited.  (An extremely obscure pattern will prevent this, but it has down sides.)  Sometimes this makes sense: it&#8217;s natural to subclass an abstract <code>List</code> class as <code>LinkedList</code>, or <code>LinkedList</code> as <code>CircularLinkedList</code>.  But sometimes this doesn&#8217;t make sense.  <code>StringBuilder</code> certainly could inherit from <code>Vector&lt;char&gt;</code>, but doing so might expose many <code>Vector</code> methods that don&#8217;t belong in the <code>StringBuilder</code> concept.  It would be more sensible for <code>StringBuilder</code> to contain a private <code>Vector&lt;char&gt;</code> which <code>StringBuilder</code> member methods manipulated.  Preventing <code>Vector</code> from being used as a base class would be one way (not necessarily the best one) to avoid this conceptual error.  But C++98 doesn&#8217;t let you easily do that.</p>
<p>Even when inheritance is desired, sometimes you don&#8217;t want completely-virtual methods.  Sometimes you&#8217;d like a class to implement a virtual method (virtual perhaps because <em>its</em> base declared it so) which derived classes can&#8217;t override.  Perhaps you want to rely on that method being implemented only by your base class, or perhaps you want it &#8220;fixed&#8221; as an optimization.  Again in C++98, you can&#8217;t do this: public virtual functions are overridable.</p>
<h2>C++11&#8242;s contextual <code>final</code> keyword</h2>
<p>C++11 introduces a contextual <code>final</code> keyword for these purposes.  To prevent a class from being inheritable, add <code>final</code> to its definition just after the class name (the class can&#8217;t be unnamed).</p>
<pre class="code" data-language="c++">
struct Base1 final
{
  virtual void foo();
};

// ERROR: can't inherit from B.
struct Derived1 : public Base1 { };

struct Base2 { };

// Derived classes can be final too.
struct Derived2 final : public Base2 { };
</pre>
<p>Similarly, a virtual member function can be marked as not overridable by placing the contextual <code>final</code> keyword at the end of its declaration, before a terminating semicolon, body, or <code>= 0</code>.</p>
<pre class="code" data-language="c++">
struct Base
{
  virtual void foo() final;
};

struct Derived : public Base
{
  // ERROR: Base::foo was final.
  virtual void foo() { }
};
</pre>
<h2>Introducing <code>MOZ_FINAL</code></h2>
<p><abbr title="Mozilla Framework Based on Templates">mfbt</abbr> now includes support for marking classes and virtual member functions as final using the <code>MOZ_FINAL</code> macro in <code>mozilla/Attributes.h</code>.  Simply place it in the same position as <code>final</code> would occur in the C++11 syntax:</p>
<pre class="code" data-language="c++">
#include "mozilla/Attributes.h"

class Base
{
  public:
    virtual void foo();
};

class Derived final : public Base
{
  public:
    /*
     * MOZ_FINAL and MOZ_OVERRIDE are composable; as a matter of
     * style, they should appear in the order MOZ_FINAL MOZ_OVERRIDE,
     * not the other way around.
     */
    virtual void foo() MOZ_FINAL MOZ_OVERRIDE { }
    virtual void bar() MOZ_FINAL;
    virtual void baz() MOZ_FINAL = 0;
};
</pre>
<p><code>MOZ_FINAL</code> expands to the C++11 syntax or its compiler-specific equivalent whenever possible, turning violations of <code>final</code> semantics into compile-time errors.  The same compilers that usefully expand <a href="http://whereswalden.com/2011/11/16/introducing-moz_override-to-annotate-virtual-functions-which-override-base-class-virtual-functions/"><code>MOZ_OVERRIDE</code></a> also usefully expand <code>MOZ_FINAL</code>, so misuse will be quickly noted.</p>
<p>One interesting use for <code>MOZ_FINAL</code> is to tell the compiler that one worrisome C++ trick sometimes isn&#8217;t.  This is the <em>virtual-methods-without-virtual-destructor</em> trick.  It&#8217;s used when a class must have virtual functions, but code doesn&#8217;t want to pay the price of destruction having virtual-call overhead.</p>
<pre class="code" data-language="c++">
class Base
{
  public:
    virtual void method() { }
    ~Base() { }
};

void destroy(Base* b)
{
  delete b; // may cause a warning
}
</pre>
<p>Some compilers warn when they instantiate a class with virtual methods but without a virtual destructor.  Other compilers only emit this warning when a pointer to a class instance is <code>delete</code>d.  The reason is that in C++, behavior is undefined if the static type of the instance being deleted isn&#8217;t the same as its runtime type <em>and</em> its destructor isn&#8217;t virtual.  In other words, if <code>~Base()</code> is non-virtual, <code>destroy(new Base)</code> is perfectly fine, but <code>destroy(new DerivedFromBase)</code> is not.  The warning makes sense if destruction might miss a base class &mdash; but if the class is marked <code>final</code>, it never will!  Clang silences its warning if the class is <code>final</code>, and I hope that <a href="https://connect.microsoft.com/VisualStudio/feedback/details/707497/msvc-should-not-emit-the-optional-warning-c4265-virtual-functions-non-virtual-destructor-for-a-class-marked-as-sealed">MSVC will shortly do the same</a>.</p>
<h2>What about <code>NS_FINAL_CLASS</code>?</h2>
<p>As with <code>MOZ_OVERRIDE</code> we had a gunky <abbr title="Cross-platform component-object model">XPCOM</abbr> static-analysis <code>NS_FINAL_CLASS</code> macro for final classes.  (We had no equivalent for final methods.)  <code>NS_FINAL_CLASS</code> too was misplaced as far as C++11 syntax was concerned, and it too has been deprecated.  Almost all uses of <code>NS_FINAL_CLASS</code> have now been removed (the one remaining use I&#8217;ve left for the moment due to an apparent Clang bug I haven&#8217;t tracked down yet), and it shouldn&#8217;t be used.</p>
<p>(Side note: In replacing <code>NS_FINAL_CLASS</code> with <code>MOZ_FINAL</code>, I discovered that some of the existing annotations have been buggy for months!  Clearly no one&#8217;s done static analysis builds in awhile.  The moral of the story: compiler static analyses that happen for every single build are vastly superior to user static analyses that happen only in special builds.)</p>
<h2>Summary</h2>
<p>If you don&#8217;t want a class to be inheritable, add <code>MOZ_FINAL</code> to its definition after the class name.  If you don&#8217;t want a virtual member function to be overridden in derived classes, add <code>MOZ_FINAL</code> at the end of its declaration.  Some compilers will then enforce your wishes, and you can rely on these requirements rather than hope for the best.</p>
]]></content:encoded>
			<wfw:commentRss>http://whereswalden.com/2011/11/26/introducing-moz_final-prevent-inheriting-from-a-class-or-prevent-overriding-a-virtual-function/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
	</channel>
</rss>
