prestococo
prestococo

Reputation: 25

How to initialize a class in C++?

I'm making a simple Binary Tree program, and I would like to initialize the left and right node. I've been trying to do it like this:

class Tree{
     Tree* left = new Tree();
     Tree* right = new Tree();
}

This is supposed to give me an accessible memory on the heap which I can use to access the left and right nodes, correct? However, it doesn't seem like that's the case. I've also tried doing this through constructors too with no luck.

Is there a way to properly initialize a class in C++? Thank you for your time.

Upvotes: 1

Views: 5726

Answers (1)

Akhil V Suku
Akhil V Suku

Reputation: 912

You can create a class like this

class Tree
{
 public:
    Tree* left;
    Tree* right;
    Tree() // default constructor
    { 
        left = nullptr;
        right = nullptr;
    }
    Tree(Tree *Tleft,Tree *Tright) // parameterised constructor
    { 
        left = Tleft;
        right = Tright;
    }

    ~Tree() // Destructor
    { 
        delete left;
        delete right; 
    }
};

you can use default constructor to initialize the Tree class as nullptr, and parameterised constructor to initialize with user values, ie with Tree nodes,

void main()
{
    Tree *node1 = new Tree(); //using default constructor
    Tree *node2 = new Tree(); //using default constructor
    Tree *node3 = new Tree(node1, node2); // using parameterised constructor
} 

Upvotes: 1

Related Questions