When a class containing virtual functions is defined in code, but the class is not used (no declaration or new), will the class's virtual tables be generated at compile time?
When a class containing virtual functions is defined in code, but the class is not used (no declaration or new), will the class's virtual tables be generated at compile time?
You can write some simple code to test your compiler:
#include <iostream>
class Foo {
public:
void Fun() {std::cout << __FUNCTION__;}
virtual void VirtualFun() {std::cout << __FUNCTION__;}
};
int main() {
Foo foo;
foo.Fun();
return 0;
}
The compilers will just ignore the class so nothing will be generated
For gcc 10.2 it will generate virtual tables and the same to msvc2019.
The existence of a virtual function table is an implementation detail, so any answer necessarily depends on the compiler being used. However, looking at one particular compiler can be informative, as long as you realize that what you observe is not required to occur.
When gcc encounters a class for which it should generate a virtual function table, the compiler looks at the class definition and picks one method based on certain conditions (see GCC Frequently Asked Questions for details). When gcc encounters the definition of that function, the virtual function table for that class is generated and included in the resulting object file (a.k.a. "emitted").
So, yes, virtual function tables are generated (by gcc, at least) even if they are not used by your program.
There is another consideration, though. The linker is allowed to omit things that it can prove are not used. If the linker has enough information to determine that a certain virtual function table is not needed, it is allowed to leave the table out of the final executable. In this case, you could end up with the situation where a virtual function table was generated by the compiler, yet it does not appear in your executable.
So if your concern is more about your executable size than your compilation time, then "yes" becomes "maybe". If a class is not used, then its virtual function table might be absent from your executable, depending on the optimizations being used.