1

I have a header file named ArrayBag.h

/** Header file for an array-based implementation of the ADT bag.
 @file ArrayBag.h */
#ifndef _ARRAY_BAG
#define _ARRAY_BAG

#include "BagInterface.h"

template<class ItemType>
class ArrayBag : public BagInterface<ItemType>
{
.
.
.
.
.
}; // end ArrayBag

#include "ArrayBag.cpp"
#endif

Then I have the i have the implementation file ArrayBag.cpp which implements some of the methods.

/* Implementation file for the class ArrayBag.
   @file ArrayBag.cpp */

#include "ArrayBag.h"

template<class ItemType> 
ArrayBag<ItemType>::ArrayBag(): itemCount(0), maxItems(DEFAULT_CAPACITY) {
}// end default constructor
.
.
.
.
.
.
 basically implement more methods 

The BagInterface class just contains virtual methods so that is not the problem but the problem seems to be an infinite recursion of the header and the code file.

for example in a test file main.cpp

#include <iostream>
#include <string>
#include "ArrayBag.h"
using namespace std;


int main(){
/// some code to test it
}

But when i run to build it I keep getting method_name function template has already been defined. I have tried removing

#include "ArrayBag.h"

but then it wont build so i just dont know I for the love of god cannot figure it out please help me I am going insane.

Talha Abid
  • 23
  • 4
  • Don't #include .cpp files in header files. Instead, compile them as separate compilation units. – Paul Sanders Aug 23 '20 at 23:47
  • 2
    Also, see https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file – cigien Aug 23 '20 at 23:47
  • At the very least, show the exact and complete error message. What's `method_name`? Where is it declared? Where is it defined? Where and how is it used? – Igor Tandetnik Aug 23 '20 at 23:48
  • @IgorTandetnik the error message is just function' : function template has already been defined and method_name is just the methods implemented in ArrayBag.cpp all of them – Talha Abid Aug 23 '20 at 23:52
  • Have you also added `ArrayBag.cpp` to the project? It won't compile, as essentially it's including itself. `main.cpp` should compile though. It's best to rename `ArrayBag.cpp` to something like `ArrayBagImpl.h`, so it's not confused for a source file meant to be compiled standalone. – Igor Tandetnik Aug 24 '20 at 00:01
  • Probably should change `_ARRAY_BAG` to `GUARD_ARRAY_BAG` (or such), because `_ARRAY_BAG` is a reserved identifier (because it begins with an underscore, and it is macro so it cuts across all scopes). – Eljay Aug 24 '20 at 00:25

0 Answers0