Reputation: 121
I know there are plenty of questions like these, but I couldn't find a solution that worked for me. Anyways, I have 4 files, two header files and two cpp files, one implementation and one main.
Header File 1
#ifndef SORTEDINTERFACE_H
#define SORTEDINTERFACE_H
using namespace std;
template<class ListItemType>
class sortedInterface
{
public:
virtual int sortedGetLength() const = 0;
virtual bool sortedIsEmpty() const = 0;
virtual bool sortedInsert(const ListItemType& newItem) = 0;
virtual bool sortedRemove(const ListItemType& anItem) = 0;
virtual bool sortedRetrieve(const ListItemType& anItem) = 0;
virtual int getItemCount () = 0;
private:
virtual int locatePosition(const ListItemType& anItem) = 0;
};
#endif // SORTEDINTERFACE_H_INCLUDED
Header File 2
#ifndef SORTED_H
#define SORTED_H
#include "sortedInterface.h"
using namespace std;
template<class ListItemType>
class sorted : public sortedInterface<ListItemType>
{
public:
sorted();
int sortedGetLength() const;
bool sortedIsEmpty() const;
bool sortedInsert(const ListItemType& newItem);
bool sortedRemove(const ListItemType& anItem);
bool sortedRetrieve(const ListItemType& anItem);
int getItemCount();
private:
static const int DEFAULT_LIST_SIZE = 10;
ListItemType items[DEFAULT_LIST_SIZE];
int itemCount;
int maxItems;
int locatePosition(const ListItemType& anItem);
};
#include "sorted.cpp"
#endif // SORTED_H
CPP File
#include "sorted.h"
#include <cstddef>
using namespace std;
template<class ListItemType>
sorted<ListItemType>::sorted() : itemCount(0), maxItems(DEFAULT_LIST_SIZE)
{
} // end default constructor
Main CPP File
#include <iostream>
#include "sorted.h"
#include <cstddef>
using namespace std;
int main()
{
sorted<string> test;
return 0;
}
When I compile I get the errors/warnings 1. redefinition of 'sorted::sorted() 2. sorted::sorted()' previously declared here
When I comment out the #include "sorted.cpp" at the end of header file #2, it works, but then in my main file, it doesn't regonize my sorted test object.
Any help would be great, thanks in advance.
Upvotes: 2
Views: 4196
Reputation: 35455
If you're adding the sorted.cpp file at the end, then you must realize that sorted.cpp is not a separate module -- it is just the implementation of your template class implementation. Therefore you should remove the first three lines from that .cpp file.
#include "sorted.h"
#include <cstddef>
using namespace std;
Those lines above should not be in the template implementation file.
Also, I would rename sorted.cpp to sorted.ipp or some other extension to something indicating it is just a template implementation file and not a separate source module to be compiled.
Upvotes: 0