...

View Full Version : C++ Class Header Problem



Trinithis
10-21-2007, 08:53 PM
I have the following header file, ListNode.h


#ifndef LISTNODE_H_
#define LISTNODE_H_

template <class E>
class ListNode {
public:
ListNode();
ListNode(E element);
E element;
ListNode<E>* next;
};

#endif


And here is the corresponding source file, ListNode.cpp


#include "ListNode.h"
#include <cstdlib>

using namespace std;

template <class E>
ListNode<E>::ListNode() {
next = NULL;
}

template <class E>
ListNode<E>::ListNode(E element) {
this->element = element;
next = NULL;
}


Here is essentially what my main.cpp is


#include <cstdlib>
#include <iostream>
#include "ListNode.h"

using namespace std;

int main() {
ListNode<int> node();
return 0;
}


Now, let me explain my problems:
If I do


node.element = 7

I get a compile error.
If I instead have


ListNode<int>* node = new ListNode<int>();
node->element = 7;
delete node;

it compiles. However, if I change the import statement to "ListNode.h", it no longer compiles. This (the change of import file extension) I don't think is an issue, but the issue of not being able to use my class without the new keyword is.

ralph l mayo
10-21-2007, 11:19 PM
Why can't I separate the definition of my templates class from it's declaration and put it inside a .cpp file? (http://www.parashift.com/c++-faq-lite/templates.html#faq-35.12)

The next few questions are also pertinent. Long story short: unlike non-template functions, the compiler always needs the definition as well as the declaration of a template function to determine what you're trying to do.

Quick fix:

Leave ListNode.cpp as it is.

Alter ListNode.h to include its own definitions:


#ifndef LISTNODE_H_
#define LISTNODE_H_

template <class E>
class ListNode {
public:
ListNode();
ListNode(E element);
E element;
ListNode<E>* next;
};

#include "ListNode.cpp" // ***

#endif


Do whatever in main, I combined most of the relevant stuff:


#include <iostream>
#include "ListNode.h"

int main() {
ListNode<int> node(12);
ListNode<int> node2;
ListNode<int>* dnode = new ListNode<int>(12);
ListNode<int>* dnode2 = new ListNode<int>;
node2.element = 12;
dnode2->element = 12;
std::cout << node.element << node2.element << dnode->element << dnode2->element;
delete dnode;
delete dnode2;
return 0;
}


All the template stuff is now in the same compilation unit:


$ g++ -Wall -Wextra -o main.out ./main.cpp && ./main.out
12121212

Trinithis
10-21-2007, 11:24 PM
Thank you so much. I spent hours trying to figure this baby out :D



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum