Search code examples
c++headervirtualinline

Can the implementation of a virtual function be put in the header file


usually if we put an implementation of a non-virtual member function in the header file that function would be inlined. how about if we put the implementation of a virtual member function in the header file? I guess it would be the same as putting it in the cpp file because inlining and polymorphism do not work together. Am I right on this?


Solution

  • Putting the implementation of a method in the header file doesn't make it inline. Putting it in the class declaration does. I'll assume that's what you meant from now on.

    What is important here is that declaring a function inline is only an information to the compiler, it does not necessarily make that function inline

    Most of the time, the compiler will just ignore this and the method won't be inlined.

    It's possible to have a virtual method inline though, as stated in the c++ faq (http://www.parashift.com/c++-faq-lite/inline-virtuals.html) : "The only time an inline virtual call can be inlined is when the compiler knows the "exact class" of the object which is the target of the virtual function call. This can happen only when the compiler has an actual object rather than a pointer or reference to an object. I.e., either with a local object, a global/static object, or a fully contained object inside a composite."

    In short, the compiler will inline a virtual method only if you don't use dynamic link resolution (we could say, "when we don't use the virtual").