0

So I wrote the code for an AVL tree and it works fine. Now I wrote another program, say Index.cpp which will have an AVL tree private member and perform some functions. For the Index constructor, I need to initialize the root of the AVL tree however I don't understand what to do.

Also, I declare the AVL tree in the Index.hpp file. When I create an Index object, the constructor for Index is called but not for AVL. So basically the AVL object is not being created. Does anyone have any recommendations why?

AVL.hpp File:

struct node{
    T key;
    S value; 
    node *left;
    node *right;
    int height;
    
    node (T key, S value){
        this->key = key;
        this->value = value;
        left = NULL;
        right = NULL;
        height = 1;
    }
};


template <class T, class S>
class AVL {
    node<T,S> *root;
    
public:
    AVL();
    AVL(T k, S s);
    ~AVL();
void setRoot(node<T,S> *p);
......
..... //some other functions as well
}

For the Index.hpp file:

class Index {
    private:
    AVL<string,LinkedList<int>> *wordsTree;
    public:
    Index(); // creates an empty Index object
    ~Index(); 
..... //other functions
}

Now I need to write the code for the Index() constructor (in .cpp file) such that the wordsTree's root is initialized. However using a parametrized constructor is not (I think) possible here and the setRoot() function gives a segmentation fault.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
Umama
  • 13
  • 3
  • please show a [mre]. Are you initialising `wordsTree` with an object? – Alan Birtles Nov 07 '21 at 18:48
  • A member initializer list (what you refer to as a "parameterized constructor") is exactly what you want. Your `AVL>*` is uninitialized, and you want to *initialize* it, so do so in the initializer list. Presumably you'll want to initialize it with `new`, which allocates raw pointers by calling a constructor. And since you're using a raw pointer here, go ahead and have a read of [Rule of Three/Five](https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three). I see you've got the destructor, which is one of the five special methods you'll need. – Silvio Mayolo Oct 02 '22 at 03:58

0 Answers0