I had referred this question (I changed its title). I am aware that code generation related to virtual
ness are implementation specific. However, earlier question suggests that, there is an additional cost related to virtual
inheritance, when calling non-virtual base method.
I wrote following test codes and checked its assembly in g++ (with -O4
):
Common part
struct Base {
int t_size;
Base (int i) : t_size(i) {}
virtual ~Base () {}
int size () const { return t_size; };
};
struct D1 : virtual Base {
int a[10];
D1 () : Base(0) {}
~D1 () {}
};
struct D2 : virtual Base {
int a[20];
D2() : Base(0) {}
~D2 () {}
};
...
void foo (Base *p)
{
if(p->size())
return;
p = 0;
}
int main ()
{
Derived d;
foo(&d);
}
Now the difference part is here:
Code 1 (normal inheritance)
struct Derived : Base {
Derived () : Base(0) {}
~Derived () {}
int a[100];
};
Code 2 (virtual inheritance)
struct Derived : virtual Base {
Derived () : Base(0) {}
~Derived () {}
int a[100];
};
Code 3 (multiple virtual inheritance)
struct Derived : D1, D2 {
Derived () : Base(0) {}
~Derived () {}
int a[100];
};
When I checked its assembly, there is no difference between all 3 versions. And following is the assembly code:
.file "virtualInheritFunctionCall.cpp"
.text
.p2align 4,,15
.globl _Z3fooP4Base
.type _Z3fooP4Base, @function
_Z3fooP4Base:
.LFB1:
.cfi_startproc
rep
ret
.cfi_endproc
.LFE1:
.size _Z3fooP4Base, .-_Z3fooP4Base
.section .text.startup,"ax",@progbits
.p2align 4,,15
.globl main
.type main, @function
main:
.LFB2:
.cfi_startproc
xorl %eax, %eax
ret
.cfi_endproc
.LFE2:
.size main, .-main
.ident "GCC: (Ubuntu/Linaro 4.6.1-9ubuntu3) 4.6.1"
.section .note.GNU-stack,"",@progbits
Does it mean that virtual
inheritance doesn't have any extra cost, when certain optimization is ON ? Do I need to perform any more complex test code to evaluate this ? Note that, without optimization, there is a difference between these assemblies.