Virtual table in class without overloading

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sat Apr 28 11:52:50 UTC 2018


On Saturday, April 28, 2018 11:04:56 Andrey via Digitalmars-d-learn wrote:
> Hello,
> I have some questions about virtual table in classes.
> Example 1:
>
> class Test
> {
>      void someMethod() { ... }
>      int anotherMethod { ... }
> }
>
> Will this class have a vtable?
>
> Example 2:
> class Test2 : Test
> {
>      void thirdMethod() { ... }
> }
>
> Will this class have a vtable?
>
> In C++ these classes don't have any vtables. What about D? In D
> all methods are virtual by default in classes. Will complier
> optimize and remove table of virtual functions because in these
> examples we see no method overloading.
>
> Thanks.

Object has virtual functions, so it's not possible to ever remove the
virtual table from a D class.

Also, even if Object didn't have virtual functions, I don't think that it
would matter, because the compiler has no way of knowing whether other code
derives from those classes and overrides those member functions (since that
would require whole program optimtization). As such, it has to treat them as
virtual. It can't devirtualize them.

If you want a class' public member function to be non-virtual, then mark it
with final. That won't get rid of the virtual table, but it will
devirtualize that function as long as its not overriding a base class
function.

Though honestly, I'm not sure why you'd even want a class without a virtual
table unless you're declaring the type as a class purely so that it's forced
to be a reference type. Otherwise, just use a struct. D structs never have
virtual tables, because they have no inheritance. Classes in D are mostly
pointless if you don't want virtual functions.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list