0

When I attempt to insert this 'food' object into my template class linked list 'test'. I get this error:

request for member ‘addNode’ in ‘test’, which is of non-class type ‘Catalog<FoodSource>()

Here's my coding, What am I doing wrong?

##main:##

int main(void)
{
    Catalog<FoodSource> test();
    FoodSource food();
    test.addNode(const &food);
    return(0);
}

##function definition in .h:##

template<class T>
class Catalog
{
    public:
        void addNode(const T& value);
};

 ##function implementation in .cpp:##

template <class T>
void Catalog<T>::addNode(const T& value)
{
    Node *temp;

    if(head == NULL)
        head = new Node (value, NULL);
    else
    {
        temp=head;

        while(temp->next !=NULL)
            temp=temp->next;

        temp->next = new Node (value, NULL);
    }
}
Michael Gruber
  • 601
  • 2
  • 11
  • 24

3 Answers3

4

You just found one of the many warts present in the C++ syntax. The standard requires that if an expression can be interpreted both as a declaration and as a definition then it must be considered as a declaration. For example your code

Catalog<FoodSource> test();

is not defining a variable named test but is instead declaring that there is a function named test that takes no arguments and that returns a Catalog<FoodSource> instance.

To define the variable you need to omit the parenthesis.

Note that there are cases where this trap is much harder to notice... for example:

double x = 3.14159;
int y(int(x));

as surprising it may seem in the above code y is declared as a function!

6502
  • 112,025
  • 15
  • 165
  • 265
  • Thanks for the link. Effective STL is exactly where I learned about this hideous trap... and where I decided I'll never waste my time writing a C++ parser. – 6502 May 03 '11 at 08:49
0

Declaration and implementation of a class template should be in the same file.

Also, you can just call test.addNode(food); in main.

Community
  • 1
  • 1
Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
  • The .h file is included in the .cpp. Calling test.addNode(food); gives me the same error. – Michael Gruber May 03 '11 at 06:56
  • @Michael: With templates this is not sufficient. The compiler needs the complete definition of the template when it is instantiated (in your case in `main`). – Björn Pollex May 03 '11 at 07:07
0

Given definition for all the classes Node, FoodSource etc is available, you need to do at least the following:

1) Move the function definition to .h file

2) The first line in main function is ambigous. It should be rewritten as Catalog<FoodSource> test; because Catalog<FoodSource> test() will be treated as function prototype

mukeshkumar
  • 2,698
  • 3
  • 19
  • 20