classes templates and constructors

I have an issue with the following code copied from a book as an example...
Xcode is giving me errors with the template constructor!!

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
  //
//  Stack.hpp
//  Example class stack
//
//  Created by James Farrow on 22/02/2017.
//  Copyright © 2017 James Farrow. All rights reserved.
//
// Fig. 14.2: Stack.h
// Stack class template.

#ifndef Stack_hpp
#define Stack_hpp

template< typename T >
class Stack {
public:
    explicit Stack( int = 10 ); // default constructor (Stack size 10)
    
    // destructor
    ~Stack() {
            delete [] stackPtr; // deallocate internal space for Stack
    }
    // end ~Stack destructor
    
    bool push( const T & ); // push an element onto the Stack
    bool pop( T & ); // pop an element off the Stack
    
    // determine whether Stack
    bool isEmpty() const {
        return top == -1;
    } // end function isEmpty
    
    // determine whether Stack
    bool isFull() const {
        return top == size - 1;
    } // end function isFull
    
private:
    int size; // of elements
    int top; // location of the top element (-1 means empty)
    T *stackPtr; // pointer to internal representation of the Stack

}; // end class template Stack

#endif /* Stack_hpp */

//
//  Stack.cpp
//  Example class stack
//
//  Created by James Farrow on 22/02/2017.
//  Copyright © 2017 James Farrow. All rights reserved.
//

#include "Stack.hpp"

// constructor template
template < typename T >
Stack< T >::Stack< int s > : size( s > 0 ? s : 10 ), // validate size
        top( -1 ), // Stack initially empty
        stackPtr( new T[ size ] ) // allocate memory for elements
    {
     // empty body
    } // end Stack constructor template

//push element onto stack
//if succesful return true, otherwise return false
template < typename T >
bool Stack< T >::push( const T & pushValue ){
    if( !isFull() ) {
        stackPtr[ ++top ] = pushvalue;
        return true;
    }
    return false;
}

//pop an element of the stack
//if successful return true, otherwise return false
template < typename T >
bool Stack < T >::pop( T &popvalue ) {
    if ( !isEmpty() ) {
        popvalue = stackPtr [ top-- ];
        return true;
    }
    return false;
}
Hi,

One shouldn't put template code in a cpp file, put it all in the header.

https://isocpp.org/wiki/faq/templates#templates-defn-vs-decl
Stack< T >::Stack(int s) : size( s > 0 ? s : 10 ), // validate size
Excellent thank you! It wasn't explained... or maybe I missed that bit 🤔
Topic archived. No new replies allowed.