C++ - What is __declspec(novtable)?

__declspec(novtable) is a Microsoft specific keyword.


It instructs the compiler to not generate vtable pointer initialization code for the class or struct. The compiler can safely omit the vtable (virtual function table) for the type, and with potentially hundreds of interfaces in a C++ project, this can result in a significant reduction in code size.


An example using __declspec(novtable):


  // IConsoleWriter is an abstract base class. It will never be instantiated directly. The vtable for this type can be discarded.
  struct __declspec(novtable) IConsoleWriter
  {
      virtual void WriteLine(char* message) = 0;
  };
  
  class ConsoleWriter : public IConsoleWriter
  {
  public:
      virtual void WriteLine(char* message) override
      {
          printf("%s\r\n", message);
      }
  };
  


Ads by Google


Ask a question, send a comment, or report a problem - click here to contact me.

© Richard McGrath