2

I have some trouble with inheritance from a template class. The code below does not compile, showing this error : main.cpp : undefined reference to OBJ1<1000>::method()

parent.h

template <int nb> class PARENT { PARENT() {}; ~PARENT() {}; virtual void method() = 0; enum { nb_ = nb }; }; 

obj1.h

#include "parent.h" template <int nb> class OBJ1 : public PARENT<nb> { virtual void method(); }; 

obj1.cpp

#include "obj1.h" template <int nb> void OBJ1<nb>::method() { //code } 

main.cpp

#include "obj1.h" int main() { OBJ1<1000> toto; toto.method(); } 

Where am I wrong ?

1 Answer 1

6

When dealing with templates you cannot split declaration and implementation into separate files. See this question for the reasons (and also for a more concise description to workaround this).

This needs to be merged (You can also #include the implementation file into the header to let the preprocessor do the merge.):

// obj1.hpp #include "parent.h" template <int nb> class OBJ1 : public PARENT<nb> { virtual void method(); }; template <int nb> void OBJ1<nb>::method() { //code } 
Sign up to request clarification or add additional context in comments.

4 Comments

The code still can't compile, but you fixed one mistake. :) Thanks.
When you define a method for a class template out of line as was done here, it's best to mark that out of line definition as inline. Without that inline, a violation of the one definition rule will result if multiple source files use that function for the same template arguments.
@DavidHammen isn't there an exception for templates? See also stackoverflow.com/q/3694899/1025391
No exception. It's the same as for a (non-template) class. If you define the function inside the class, the function is inline by default. There's no need for the inline keyword for functions defined in line because it's already inline. By default. You separated the definition from the declaration. The same rules apply as for a class: If you don't qualify an out of line definition with the inline keyword, the function isn't an inline function. In C++, the primary purpose of inline is with regard to the one definition rule. That the function might be inlined; that's just a hint.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.