user00239123
user00239123

Reputation: 278

Sorted lists in C++

I am studying data structure course and have been asked to create a sorted list, however I get an error whenever trying to declare a variable that use datatype. Here is what I have done so far

#include<iostream>

using namespace std;
int main(){
  List<int> x;
  // Other Code for testing
}
const int MAX_ITEMS = 30;
template<class T>
class List{
private:
  int size;
  int currIndex;
  T data[MAX_ITEMS];
public:
    // list functions
};

However when compiling this I get an error:

$ g++ sortedList.cpp
sortedList.cpp:5:3: error: use of undeclared identifier 'List'
  List<int> x;
  ^
sortedList.cpp:5:11: error: expected '(' for function-style cast or type
      construction
  List<int> x;

The error is with this line List<int> x;, isn't that how we are supposed to declare variables with templates?

Full code can be found here: https://pastebin.com/T2hXDxAP

Upvotes: 0

Views: 66

Answers (1)

Arnav Borborah
Arnav Borborah

Reputation: 11779

Suppose you were the compiler. You are reading the file from the top down, and you encounter this:

List<int> x;

When the compiler sees this, it goes:

WTF! I've never seen that before. Is it an identifier? Let me check... Nope! Nothing before main or in main! Random gibberish? Yes, let's create an error!

So the compiler creates an error. To fix this, you need to define the class before main. (You cannot forward declare the class as it is a template, which needs to be defined before it is used More info can be found here).

Upvotes: 2

Related Questions