0

I am trying to implement a Stack as a custom template class and I want to declare my functions in a .cpp file rather than the header.

This is my header:

#ifndef _STACK_H
#define _STACK_H

#include <iostream>

const int MAX_STACK = 30;

template<class StackItemType>

class Stack {
public:
    Stack();

    bool isEmpty();

    bool push(const StackItemType newItem);

    bool pop();

    bool pop(StackItemType &currentTop);

    bool getTop(StackItemType &currentTop) const;

private:
    StackItemType items[MAX_STACK];
    int top;
};

#endif //_STACK_H

And this is what I am trying to do in my .cpp:

//Constructor
template<class StackItemType>
Stack<StackItemType>::Stack() {
    top = -1;
}

But when I try to build the project, it throws an error as below

Undefined symbols for architecture x86_64:
  "Stack<double>::Stack()", referenced from:
      (anonymous namespace)::evaluatePrefix(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >) in main.cpp.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
ninja: build stopped: subcommand failed.

I am not posting other classes because when I put my functions in the header everything runs perfectly so I believe I am doing something wrong when I am trying to separate functions.

DenTun
  • 11
  • 3
  • 1
    You can implement the functions outside but they need to be implemented in a header. – drescherjm May 10 '22 at 14:21
  • A bit about terminology: in `class Stack { Stack(); }` the `Stack();` is a **declaration** of the default constructor; the code `Stack::Stack() { top = -1; }` is a **definition** of that member. You **cannot** declare members outside of a class definition. You can define member functions inside the class definition or outside it. – Pete Becker May 10 '22 at 15:45

0 Answers0