1

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 ?

Patouf
  • 119
  • 4
  • 15

1 Answers1

5

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
}
Community
  • 1
  • 1
moooeeeep
  • 31,622
  • 22
  • 98
  • 187
  • The code still can't compile, but you fixed one mistake. :) Thanks. – Patouf Oct 09 '12 at 10:11
  • 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. – David Hammen Oct 09 '12 at 10:13
  • @DavidHammen isn't there an exception for templates? See also http://stackoverflow.com/q/3694899/1025391 – moooeeeep Oct 09 '12 at 10:39
  • 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. – David Hammen Oct 09 '12 at 11:29