Discussion:
classInstanceSize and vtable
Etienne Cimon via Digitalmars-d-learn
2014-10-24 00:01:15 UTC
Permalink
I'm trying to figure out the size difference between a final class and a
class (which carries a vtable pointer).

import std.stdio;

class A { void print(){} }

final class B { void print(){} }

void main(){
writeln(__traits(classInstanceSize, A));
writeln(__traits(classInstanceSize, B));
}


Returns:
8
8

I'm not sure, why does a final class carry a vtable pointer?
bearophile via Digitalmars-d-learn
2014-10-24 00:12:19 UTC
Permalink
Post by Etienne Cimon via Digitalmars-d-learn
I'm not sure, why does a final class carry a vtable pointer?
In D all class instances contain a pointer to the class and a
monitor pointer. The table is used for run-time reflection, and
for standard virtual methods like toString, etc.

Bye,
bearophile
Etienne Cimon via Digitalmars-d-learn
2014-10-24 00:21:52 UTC
Permalink
In D all class instances contain a pointer to the class and a monitor
pointer. The table is used for run-time reflection, and for standard
virtual methods like toString, etc.
Bye,
bearophile
So what's the point of making a class or methods final? Does it only
free some space and allow inline to take place?
bearophile via Digitalmars-d-learn
2014-10-24 06:18:43 UTC
Permalink
Post by Etienne Cimon via Digitalmars-d-learn
So what's the point of making a class or methods final?
It forbids subclassing. And final methods are not virtual, so
they can be inlined.

Bye,
bearophile
Simen Kjaeraas via Digitalmars-d-learn
2014-10-24 06:33:33 UTC
Permalink
Post by Etienne Cimon via Digitalmars-d-learn
Post by bearophile via Digitalmars-d-learn
In D all class instances contain a pointer to the class and a
monitor
pointer. The table is used for run-time reflection, and for
standard
virtual methods like toString, etc.
Bye,
bearophile
So what's the point of making a class or methods final? Does it
only free some space and allow inline to take place?
Like bearophile said the vtable is required for virtual methods.
Consider this code:

import std.stdio : writeln;

class A { void foo() {writeln("A");} }
final class B : A { override void foo() {writeln("B");} }

void main() {
A a = new B();
a.foo();
}

In order for the call to foo to run the correct version of foo, B
needs to have a vtable. Since all classes in D implicitly inherit
from Object, which has some virtual methods, all classes need to
have a vtable.

--
Simen

Loading...