moiself
moiself

Reputation: 55

pure virtual class, only 1 derived class, still vtable?

my question is rather simple, if you have an pure virtual class (interface) but due the current active build, only 1 derived class is compiled, will there still be a vtable created ?

class Foo
{
    virtual void bar() = 0;
}
#if 1
class Foo_1 : public Foo
{
void bar() {cout<<"foo_1";}
}
#else
class Foo_2 : public Foo
{
void bar() {cout<<"foo_2";}
}
#endif

their is (as far as I can tell) no need for a vtable in this case.

So will this get optimised or do you still get the overhead of the vtable ?

thx

Upvotes: 0

Views: 289

Answers (3)

Andrew Tomazos
Andrew Tomazos

Reputation: 68678

This is a potential link-time optimization (but clearly cannot be made at compile-time).

Upvotes: 1

ldav1s
ldav1s

Reputation: 16305

You'll probably get the overhead of the vtable, because classes can always be subclassed (if the contents of your sample code are in a header):

class Foo_3 : public Foo_1 {
     void bar() { Foo_1::bar(); ... }
}

If all the code is in the same translation unit, the compiler might be able to figure it all out.

Upvotes: 0

jjlin
jjlin

Reputation: 4703

You'll still get the vtable. After all, the compiler doesn't know if class Foo will be used in some other translation unit. Or maybe you'll package it up as a library and some other user will derive from Foo; again, the compiler doesn't know a priori.

Upvotes: 0

Related Questions