Reputation: 269
I have a private variable of type struct node (note that the struct node has left,right and parent pointers as well as the property: T value
, where T is a template type) in a header file:
node<T>* root
I then have the following method in a .cpp file:
template<> void RedBlack<int>::setRoot(int elem) {
root->value=elem;
}
However when I try to create an instance of the class in the main method and then try to set the value of the root from there, I get a runtime error: bad access.
Any idea as to what is wrong? P.S. Still new to the 'templates' concept.
Upvotes: 0
Views: 473
Reputation: 3397
Did you allocate the memory for the object root points to?
node<T>* root = new node<T>();
You need to allocate the object referenced by the pointer before it can be used. If you don't, it is pointing to "nothing" and dereferencing it will do bad things (exception if it points to NULL, use garbage if it points to an old instance or some other object, etc.)
Also, you variable, the pointer needs to "live" somewhere.
The best place is probably in a class that contains root:
class MyClass
{
private:
node<T>* root;
public:
MyClass() // Constructor
{
root = new node<T>();
}
~MyClass() // Destructor
{
// NOTE: If root contains pointers, you need to delete the objects
// they point to as well.
delete root;
}
// Add functions to do something with root...
};
Upvotes: 0
Reputation: 110668
I have a private variable of type
struct node
in a header file
No you don't! What you actually have is a pointer to a node<T>
. It doesn't point at a valid node
object until you tell it to. If you try to dereference a pointer that isn't yet pointing at a valid object (which is what happens when you do ->
on it), you have undefined behaviour. Your lucky that your environment is giving you a nice error. Anything could have happened.
You're going to have to create a node<T>
. One way to do this, if your class is always going to have a root node, is to simply make the member a node<T>
, rather than node<T>*
. Then the root node is part of the class. Otherwise you can dynamically allocate it, by doing:
root = new node<T>();
However, dynamic allocation is not recommended. You will have to remember to delete root;
in the destructor of your class, or you might end up with memory leaks. It'll also mean providing a user-defined copy constructor and assignment operator to avoid leaks as well. Instead, if you need a dynamically allocated node
, you should look up smart pointers.
Upvotes: 1