PATCH: Implement __attribute__((final)) for C++, restricting subtyping and overriding

Jeffrey Yasskin jyasskin@gmail.com
Sat Oct 11 04:58:00 GMT 2008


On Fri, Oct 10, 2008 at 1:04 PM, Doug Gregor <doug.gregor@gmail.com> wrote:
> On Fri, Oct 10, 2008 at 1:53 PM, Jeffrey Yasskin <jyasskin@gmail.com> wrote:
>> Hi all.
>>
>> I've implemented __attribute__ ((final)) for C++ classes and virtual
>> member functions. It behaves very similarly to Java's final keyword:
>> when applied to a class, it prevents anyone from subtyping that class;
>> and when applied to a virtual member function, it prevents any
>> subtypes from overriding that function. The patch shouldn't affect any
>> code that doesn't use the attribute. In theory, knowing that a method
>> is the final override could allow g++ to, in some cases, emit static
>> calls instead of virtual calls, but I haven't implemented that here.
>
> Does this implement exactly the behavior required for the "final"
> attribute that just went into C++0x?
>
>  http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2761.pdf

I think it implements the same behavior on virtual functions, but may
be different on classes. In particular, the draft standard says, "If
the attribute is specified for a class definition, it is equivalent to
being specified for each virtual member function of that class,
including inherited member functions." To me, that says that the
following code would be legal:

class Base [[final]] {
  void foo();
  virtual void bar();
};

class Derived : public Base {
  // Just don't override bar(), and you're fine.
};

My patch would complain about deriving any class from a final class,
even if the final class had no virtual functions. I think my behavior
makes more sense -- enough more that the definition in the draft
standard looks like a mistake -- but if you don't think it's likely to
change I'll change my patch to implement that instead.

The location of the attribute also seems to be different, since gcc
wants me to write "class __attribute__((final)) Base", and the draft
standard wants me to write "class Base [[final]]". I could be
misunderstanding that, and it may naturally fix itself as C++0X
attributes get implemented.

Thanks for taking a look,
Jeffrey


More information about the Gcc-patches mailing list