While going through runtime, I'm getting a nullptr exception while this code is executing.
bool Tree::Insert(int n)
{
if (root == nullptr) // This is where it throws
{
Node* root = new Node(n);
return true;
}
Initialization in Tree.h
private:
Node* root;
and Tree constructor.
Tree::Tree()
{
root = nullptr;
}
I have coded exactly like this before and it never threw an exception.
UPDATE: I apologize for the confusion on the extra '}' Tree::Insert(). There's more code in there and they all have a return case. I had this before
Node* newNode = new Node(n);
root = newNode;
but changed it for a different reason.
Node.h
#pragma once
struct Node
{
int data;
Node *left;
Node *right;
// Constructor
Node() { data = 0; left = nullptr; right = nullptr; }
// Parameterized
Node(int d) { data = d; left = nullptr; right = nullptr; }
// Destructor
~Node() { data = 0; }
};