Silviu
Silviu

Reputation: 709

Binary tree with classes

I have this piece of code:

class Node{
public:
    Square square;
    Node *NW;
    Node *NE;
    Node *SW;
    Node *SE;

};

int main()
{
    Square s(2,3,1);
    Node *root;

    root->square=s;
    cout<<root->square.length();

}

Square is a class I created. But when I run this code I get segmentation fault 11. Basically I want to use an object of class Square, as data type of a tree, and length is a function of the square object. Why is this wrong?

Upvotes: 0

Views: 517

Answers (2)

cloudiebro
cloudiebro

Reputation: 133

root = new node;
root -> squares = s;
delete root;
root = NULL;

You need to allocate memory for the pointer. You are trying to dereference a pointer that hasn't been allocated. That's why you are segfaulting.

Upvotes: 0

Cory Kramer
Cory Kramer

Reputation: 117856

You should declare your Node on the stack

int main()
{
    Square s(2,3,1);
    Node root;

    root.square = s;
    cout << root.square.length();
}

The current problem is that you're using an uninitialized, unallocated pointer. If you want to stick to a pointer (which there's no reason to in this case), you'd need to new it (then remember to delete it too).

int main()
{
    Square s(2,3,1);
    Node *root = new Node;

    root->square = s;
    cout << root->square.length();

    delete root;
}

In modern C++ if you do need a pointer (e.g. if the class is polymorphic, etc) you should prefer a smart pointer instead of a raw pointer.

int main()
{
    Square s(2,3,1);
    auto root = std::make_unique<Node>();

    root->square = s;
    cout << root->square.length();
}

Upvotes: 3

Related Questions