Templates and Inheritance

Started by
2 comments, last by Chris Hare 19 years, 7 months ago
This code gives a linker error:

// engine_container.hpp

#ifndef _ENGINE_CONTAINER_HPP_
#define _ENGINE_CONTAINER_HPP_

#include "globals.hpp"
#include <vector.h>


template <typename t_type>
class Engine_container_interface
 {
  public:
  Engine_container_interface() { }
  virtual bool m_add_stuff(t_type *a_stuff, ID &a_new_stuff_id) { }
 }; // end class Engine_container_interface
 
 
 
 
template <typename t_type>
class Engine_container_STL : public Engine_container_interface<t_type>
 { 
  public:
  Engine_container_STL();
  virtual bool m_add_stuff(t_type *a_stuff, ID &a_new_stuff_id);
  protected:
  vector<t_type> m_stuff_vector;
  ID m_references;
 }; // end class Engine_container_STL
 
#endif // #ifndef _ENGINE_CONTAINER_HPP_




// engine_container.cpp

#include "engine_container.hpp"

template <typename t_type>
bool Engine_container_STL<t_type>::m_add_stuff(t_type *a_stuff, ID &a_new_stuff_id)
 {
  m_stuff_vector.push(*a_stuff);
  a_new_stuff_id = m_stuff_vector.size();
 }

template <typename t_type>
Engine_container_STL<t_type>::Engine_container_STL()
 {
  m_references = 0;
 } // end Engine_container_STL<t_type>::Engine_container_STL()




And when i try to :


Engine_container_interface<VERTEX> *verts_container;

...

verts_container = new Engine_container_STL<VERTEX>;

i get 2 linker errors: [Linker error] undefined reference to `Engine_container_STL<VERTEX>::Engine_container_STL()' [Linker error] undefined reference to `Engine_container_STL<VERTEX>::Engine_container_STL()' What am i doing wrong?
Advertisement
Your constructor has no body. (Clarification: it should be written inside the class definition, not outside, as most compilers/linkers do not support this)
Unless I'm missing something, you need to put the code in the header file for templates.

Jeff Thompson
There are a few errors here.
Note: I assume you are using a handcrafted vector, because the correct header would then be <vector>, not <vector.h>, and std::vector lives in namespace std and has no push() function.

To begin with, neither m_add_stuff() functions return a value.
Also, define the m_add_stuff() function in the .hpp file [later you can learn how to use .inl files], and inside the #ifndef #endif commands.

That's about it.

This topic is closed to new replies.

Advertisement