redefinitin of ______ previoulsy declared here

Hello,
I have this annoying error 'redefinitin of ______ previoulsy declared here', and both them point to the same line.

Now I know that this can be solved by implementing guards at the beginning of .h files, but that doesn't seem to work for me now. Does anyone know what's happening here?

1
2
3
4
5
6
7
8
9
10
11
12
13
#ifndef _STACK_INTERFACE_H_
#define _STACK_INTERFACE_H_

template<class ItemType>
class StackInterface
{
public:
   virtual bool isEmpty() const = 0;
   virtual bool push(const ItemType& newEntry) = 0;
   virtual bool pop() = 0;
   virtual ItemType peek() const = 0;
}; // end StackInterface
#endif 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

#ifndef _ARRAY_STACK_H_
#define _ARRAY_STACK_H_

#include "StackInterface.h"

const int MAX_STACK = 5;

template<class ItemType>
class ArrayStack : public StackInterface<ItemType>  //<- this is where error show up
{
private:
	ItemType items[MAX_STACK];
	int      top;

public:
	 ArrayStack();
	 bool isEmpty() const;
	 bool push(const ItemType& newEntry);
	 bool pop();
	 ItemType peek() const;
};

#include "ArrayStack.cpp"
#endif 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include "ArrayStack.h"

template<class ItemType>
ArrayStack<ItemType>::ArrayStack() : top(-1)
{
}

template<class ItemType>
bool ArrayStack<ItemType>::isEmpty() const
{
	return top < 0;
}

template<class ItemType>
bool ArrayStack<ItemType>::push(const ItemType& newEntry)
{
	bool result = false;
	if (top < MAX_STACK - 1)
	{
		top++;
		items[top] = newEntry;
		result = true;
	}

	return result;
}


Only other file I have is the one containing my main, and that is currently empty.
I wouldn't implement your templates in a source file that is included in a header file. I don't know for certain if that's what is causing your error, but I would make sure you aren't trying to compile ArrayStack.cpp, probably by renaming to something like ArrackStack.implementation or whatever. It also should not need to include its ArrayStack.h since it is just the header implementation.
As @Zhuge suggested, your problem is declaring the templated functions in a separate file. Try to move all the declarations from the .cpp file back to the .h file and it should work (unless you have other errors which I didn't really look for).

Quote from The C++ Standard Library: A Tutorial and Handbook

The only portable way of using templates at the moment is to implement them in header files by using inline functions.


Kind regards,
Raul.
Topic archived. No new replies allowed.