So if I have a header file like this:

template<typename T>
class  snake 
{
public:
   void example();

private:
    T *start_Ptr;
};

and then a source file like this:

#include <iostream>
#include <stddef.h>		
#include "foo.h"

using namespace std;


template<class T>
struct node
{
    T data;
    node *next;
};

template<typename T>
void snake<T>::example()

{
    node<int>* temp = start_Ptr;
	cout<<"Does this work?";
}
void main()
{
	snake<int> show;
	show.example();
}

Why do I get this message?
error C2440: 'initializing' : cannot convert from 'int *' to 'node<T> *'
I know if I did something like node* start_Ptr=0; that would work but how would I do it with start_Ptr under private?

Recommended Answers

All 5 Replies

template<class T> 
class snake; 

template<class T>
struct node
{
    T data;
    node *next;
};


template<class T>
class  snake 
{

// . . .
private:
     node *start_ptr;

// . . .

};

Your startptr is of type T and you are trying to equate it to another pointer of type struct node*

I think you need something like this.

template <typename T>
struct node
{
    T data;
    struct node<T> *next;
};

template<class T>
class  snake 
{
public:
   void example();

private:
    struct node<T> *start_Ptr;
};


template<class T>
void snake<T>::example()
{   
  struct node<T> *temp = start_Ptr;
	cout<<"Does this work?";
}

void main()
{
	snake<int> show;
	show.example();
}

neither of your answers worked

neither of your answers worked

No they seem to work out fine.

Its just that the template node should be declared before template snake does.

Just by doing that. the second example works.

#include <iostream>
#include <stddef.h>

using namespace std;


template<class T>
struct node
{
    T data;
    node *next;
};

template<class T>
class  snake
{
public:
   void example();

private:
    node<T> *start_Ptr;
};





template<class T>
void snake<T>::example()

{
    node<T>* temp = start_Ptr;
	cout<<"Does this work?";
}
int main()
{
	snake<int> show;
	show.example();
}

This is what i have done and it seems to compile without errors.

The answer is simple:
If you are using templates, you can't have header and source code. Everything has to be in one file.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.