Search code examples
c++objectnested-classinternal-class

constructing a class with a struct inside of it c++


So I have a class which holds a struct inside its private variables and inside this struct I have an array where the size of the array is only determined after the construction of the class.

template <typename T> 
class btree {

  public:
    btree(size_t maxNodeElems);
    ~btree() {}

  private:
    // The details of your implementation go here
    size_t maxNodeElems;
    struct node {

      list <T> elements;
      node lvl[];

    };

};

Firstly, do I have to make it so its node * lvl and how do I call the variables inside this struct? Is it the same as a private variable, so whenever I use it inside one of the functions in btree class I can call it be btree.lvl or is it btree->node->lvl or is there a special way to do this?

Also, my array has to be of maxNodeElems+1 if someone can help me, that'd be much appreciated!


Solution

  • You are just declaring the type, not an actual object of that type. You need to make your struct declaration public and the object private:

    template <typename T> 
    class btree {
    
      public:
        btree(size_t maxNodeElems);
        ~btree() {}
    
        struct node {   // <- this is just a declaration of a private inner-class
          list <T> elements;
          node lvl[];
        };
    
      private:
        size_t maxNodeElems;
        node*  memberNode;   // <- this is the actual private member
    
    };
    

    You can create objects of that type from outside:

    btree<A>::node* n = new btree<A>::node;
    

    For accessing members, you can have public getters & setters in your btree class:

    class btree {
    public:
       node* getNode()
       {
          return memberNode;
       }
       //...........
       //...........
    };
    

    EDIT:

    The following works for me (initializing the member):

    template <typename T> 
    class btree {
    
      public:
        btree()
        {
           memberNode = new btree<T>::node;
        }
        ~btree() {}
    
        void init()
        {
           memberNode->lvl = new node[10];
        }
    
        struct node {   // <- this is just a declaration of a private inner-class
          list <T> elements;
          node* lvl;
        };
    
      private:
        size_t maxNodeElems;
        node*  memberNode;   // <- this is the actual private member
    
    };
    
    int _tmain(int argc, _TCHAR* argv[])
    {
       btree<char> b;
       b.init();
    }