Newbie: Templates complication

R

Rach

Hi,

Is it possible for me to create a class Node that has a pointer to a class
Node. i.e.:

template <class T> class Node {
public:
Node (T t, int n) { ptrChild = t; nValue = n; };
private:
T* ptrChild;
int nValue;
};

How do I instantiate such class?

thanks much,
Rach
 
K

Karl Heinz Buchegger

Rach said:
Hi,

Is it possible for me to create a class Node that has a pointer to a class
Node. i.e.:
Sure


template <class T> class Node {
public:
Node (T t, int n) { ptrChild = t; nValue = n; };

From the way you use 't', I think it must be
Node (T* t, int n) { ptrChild = t; nValue = n; };
private:
T* ptrChild;
int nValue;
};

How do I instantiate such class?

eg.
struct Test
{
int a, b;
};

Test StructA;
Node<Test> NodeA( &StructA, 3 );
 
J

John Harrison

Rach said:
Hi,

Is it possible for me to create a class Node that has a pointer to a class
Node. i.e.:

template <class T> class Node {
public:
Node (T t, int n) { ptrChild = t; nValue = n; };
private:
T* ptrChild;
int nValue;
};

I think perhaps you mean this

template <class T> class Node {
public:
Node (Node<T>* t, T n) { ptrChild = t; nValue = n; };
private:
Node<T>* ptrChild;
T nValue;
};
How do I instantiate such class?

Same as any other class. Classes containing pointers to their own type
aren't a problem in C++, even when they are templates.
thanks much,
Rach

john
 
R

Rach

template <class T> class Node {
public:
Node (Node<T>* t, T n) { ptrChild = t; nValue = n; };
private:
Node<T>* ptrChild;
T nValue;
};

How do I instantiate this class? Node trial = Node<Node<Node>>; doesn't
work.

Thanks much,
Rach
 
K

Karl Heinz Buchegger

Rach said:
template <class T> class Node {
public:
Node (Node<T>* t, T n) { ptrChild = t; nValue = n; };
private:
Node<T>* ptrChild;
T nValue;
};

How do I instantiate this class? Node trial = Node<Node<Node>>; doesn't
work.

Node<int> trialA( NULL, 2 );
Node<int> trialB( trialA, 3 );
 
J

John Harrison

Rach said:
template <class T> class Node {
public:
Node (Node<T>* t, T n) { ptrChild = t; nValue = n; };
private:
Node<T>* ptrChild;
T nValue;
};

How do I instantiate this class? Node trial = Node<Node<Node>>; doesn't
work.

Thanks much,
Rach

I think you are confused, T is the type of data that each node holds, it has
nothing to do with the fact that each node points to another node.

Node<int> trial(NULL, 123);

john
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top