0

I've got a class that uses a two-arguments template:

template<class T, class R>

When I try to declare an object in main.cpp it says: "undefined reference to FileTest<int, int>::FileTest()

Here's the code:

FileTest.h

#ifndef FILETEST_H
#define FILETEST_H
#include <string>
#include <iostream>

....

using namespace std;

template<class T, class R>
class FileTest : public FileInput , FileOutput
{

    public:
        FileTest();

        FileTest(const string nome_file):FileInput(nome_file),FileOutput(nome_file){
        };

        virtual ~FileTest();

        void setNewEntry(const T id_domanda,const R id_risposta);

        ...



    private:
        ...

};
template<class T, class R>
FileTest<T,R>::~FileTest()
{
    //dtor
}


template<class T, class R>

void FileTest<T, R>::setNewEntry(const T id_domanda,const R id_risposta){
  /*
    sets new entry in a vector
*/


}

#endif // FILETEST_H

main.cpp

 #include <iostream>

    #include "FileTest.h"

    using namespace std;

int main()
{

    FileTest<int, int>  object;
    return 0;
}

Error (in main.cpp) :

undefined reference to FileTest<int, int>::FileTest()

When I try with another class which has only one template argument, everything is working! What's the cause of this error?

2 Answers2

2

You declared a zero parameter constructor for FileTest:

template<class T, class R>
class FileTest : public FileInput , FileOutput
{

    public:
        FileTest();

But I can't see an implementation for that method anywhere. As this is a constructor for a template class, its implementation should be in the header file somewhere.

Dutow
  • 5,638
  • 1
  • 30
  • 40
2

Problem

You have declared constructor without parameters

FileTest();

but didnt provide his definition anywhere, so linker won't find it and this will result in "undefined reference to" if you would attempt to call this function.

This constructor without paramters is called when constructing object in main FileTest<int, int> object;)


Fix

Change constructor to

FileTest() {}

or

FileTest() = default;
kocica
  • 6,412
  • 2
  • 14
  • 35