template and inheritance

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sunnyleekr
    New Member
    • Aug 2008
    • 1

    template and inheritance

    Hi, I am having trouble compiling the simple code below...

    //leader.hpp
    #ifndef LEADER_HPP
    #define LEADER_HPP
    class leader
    {
    public:
    leader(){}
    virtual ~leader(){}
    virtual void hahaha()=0;
    virtual void hahahaha()=0;
    };
    #endif

    //soldier.hpp
    #ifndef SOLDIER_HPP
    #define SOLDIER_HPP
    #include "leader.hpp "

    template <class T>
    class soldier : public leader
    {
    public:
    soldier(){}
    virtual ~soldier(){}
    virtual void hahaha();
    virtual void hahahaha();
    };
    #endif
    //soldier.cpp
    #include "soldier.hp p"

    template <class T>
    void soldier<T>::hah aha()
    {

    }

    template <class T>
    void soldier<T>::hah ahaha()
    {

    }

    // test.cpp
    #include "leader.hpp "
    #include "soldier.hp p"

    int main(void)
    {
    leader *a;

    a=new soldier<int>();

    delete a;

    return 0;
    }

    when I compile with g++, I get these errors:

    g++ -o "test" test.o soldier.o
    test.o:(.rodata ._ZTV7soldierIi E[vtable for soldier<int>]+0x10): undefined reference to `soldier<int>:: hahaha()'
    test.o:(.rodata ._ZTV7soldierIi E[vtable for soldier<int>]+0x14): undefined reference to `soldier<int>:: hahahaha()'
    collect2: ld returned 1 exit status

    Is there something wrong with the code??
    thanks,
    sunny
  • Airslash
    New Member
    • Nov 2007
    • 221

    #2
    I'm going to take a guess here, but you define Soldier as a Template class, but your Constructor doesn't support templates.

    Comment

    • newb16
      Contributor
      • Jul 2008
      • 687

      #3
      You should either explicit instantiate soldier<int> in soldier.cpp or move soldier<T>::hah a() body to header file - compiler doesn't know at the time it compiles soldier.cpp that there will be soldier<int> in main.cpp.

      Comment

      Working...