0

How to initialize the array-like member variable?

The visual studio code says:

no matching function for call to 'Node::Node()' gcc line 12 col 9

const int N = 100;

struct Node {
    int val, ch[2];
    /**
    void init(int _val) {
        this->val = _val, this->ch[0] = this->ch[1] = 0;
    }*/
    Node (int _val): val(_val) {
        this->ch[0] = this->ch[1] = 0;
    }
} tree[N];    // <--------- this is line 12


int main() {
    int a;
    cin >> a;
    tree[0] = Node(a);
}
xaero
  • 215
  • 1
  • 2
  • 6
  • 3
    The error is complaining about `tree[N]`, not `ch[2]`. Like the error says, you need to give your class a default constructor. If you don't want to do that, you need to specify an initializer for each array element. – NathanOliver Sep 15 '22 at 13:12
  • Or simply use a `std::vector` with `push_back`/`emplace_back` instead of an array, which doesn't require you to immediately (default-)construct all elements. – user17732522 Sep 15 '22 at 13:13
  • Could you please give a code demo? – xaero Sep 15 '22 at 13:14
  • Refer to [how to ask](https://stackoverflow.com/help/how-to-ask) where the first step is to *"search and then research"* and you'll find plenty of related SO posts for this. – Jason Sep 15 '22 at 13:15
  • And if your introductory book doesn't explain how to write default constructors, get a [better one](https://stackoverflow.com/q/388242/212858) – Useless Sep 15 '22 at 13:16
  • why do you call it "array-like" ? It is an array – 463035818_is_not_an_ai Sep 15 '22 at 13:18

1 Answers1

3

The problem is that when you wrote tree[N] you're creating an array whose elements will be default constructed but since there is no default constructor for your class Node, we get the mentioned error.

Also, Node doesn't have a default constructor because you've provided a converting constructor Node::Node(int) so that the compiler will not automatically synthesize the default ctor Note::Node().


To solve this you can add a default ctor Node::Node() for your class.

Jason
  • 36,170
  • 5
  • 26
  • 60