Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Rhalliwell1

macrumors 6502a
Original poster
May 22, 2008
588
1
I am having a problem writing the nodes for the list. I want to return the pointer to the next node but i am getting errors

Node.h :

Code:
#ifndef Node_H
#define Node_H

template <typename T>
class Node {
private:
	Node* ptr; //points to the next node;
	T* obj; //value to be stored within the node;

public:
	//constructors
	Node(T* theObj, Node* ptr);
	//copy constructor
	Node(Node& n);

	T* getNext();
	T* getObj();	
};
#endif


Node.cpp :

Code:
#include "Node.h"

template<typename T>
Node<T>::Node(T* theObj, Node* thePtr){
	obj = theObj;
	ptr = thePtr;
}

template<typename T>
Node<T>::Node(Node& n) {
	ptr = n.getNext;
	obj = n.getObj;
}

template<typename T>
T* Node<T>::getObj() {
	return obj;
}

Node* Node::getNext() {
	return ptr;
}

error is at line 20 -------> Node* Node::getNext() {
 
Slightly hard to find the problem, because you didn't say what kind of error you get (really helpful information), but when I read through your header file, there was one method where I thought: "Huh? That can't be right" and if you read the error message carefully, you will probably find what's wrong.

By the way, do you really want these constructors to be public?
 
chown is right. You have a mismatch there. Also, usually with templated classes you'll want to put the code in the .h file either inline or below the class def. Otherwise if you try to include node.h from another file, then it won't work. Or, you'd have to include node.cpp as well.

Good luck.
 
While we're criticizing the design anyway, I'd ask why you are storing T* instead of T.
 
Is writing "node * ptr" true? we should have written :Node<T>*ptr; ,shouldn't we?
:confused:

I would have thought all references to Node would have to be Node<T> including in obj's declaration, the constructor parameters, and getNext()'s return type.

Code:
template<typename T>
Node<T>* Node<T>::getNext() {
	return ptr;
}


While we're criticizing the design anyway, I'd ask why you are storing T* instead of T.

One possibility is that this is a linked list providing a view over another data structure, so obj points into the other data structure. This would explain the lack of destructor deallocating obj. But I think that unlikely. I think it's more likely to be two mistakes.


But I have a greater question. Why is the OP trying to implement his own linked list instead of using the Standard Template Library?
 
Last edited:
But I have a greater question. Why is the OP trying to implement his own linked list instead of using the Standard Template Library?

I assumed it was for education. I didn't notice the thread-necro either, so I'll stop posting in here.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.