1

I can't seem to get this right.

class Tree
{
    Node*   root;
    vector& dict;
} 

class Node
{
    vector& dict;
    char*   cargo;
    Node    left;
    Node    right;
}

I want each instance of Tree to have it's own dict, and I want it to pass a reference to the dict to the node constructor, which would recursively pass the reference to each child node so that each Node can enter a pointer to itself in the dict.

I'm having a lot of trouble with the syntax to:

  • get the vector initialized
  • pass a reference to the vector to the Node constructor
  • receive the reference in the Node constructor

I know this stuff is pretty basic. I'm teaching myself c++.

Thanks

Luc Touraille
  • 79,925
  • 15
  • 92
  • 137
Peter Stewart
  • 2,857
  • 6
  • 28
  • 30

2 Answers2

3

You haven't specified what you've tried that isn't working, but I suspect you are having trouble in the constructors because a reference can't be assigned to; you have to initialize it.

Also, when you use std::vector, you have to use a template parameter for the element type. So you can't just use vector&, you need vector<Something>&, where Something is whatever the element type is.

So, you probably want something like this:

class Tree
{
private:
    Node* root;
    std::vector<Something>& dict;

public:
    Tree(Node* aRoot, std::vector<Something>& aDict): root(aRoot), dict(aDict) {}
};

class Node
{
private:
    std::vector<Something>& dict;
    char*cargo;
    Node left;
    Node right;

    Node(std::vector<Something>& aDict, char* aCargo): dict(aDict), cargo(aCargo) {}
};
Kristopher Johnson
  • 81,409
  • 55
  • 245
  • 302
2

You can initialize a reference only in an initialization list of a constructor. For instance,

Tree::Tree( vector<type>& d ) : dict(d) 
{
  ...
}
Kirill V. Lyadvinsky
  • 97,037
  • 24
  • 136
  • 212