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);
}
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. Commented Sep 15, 2022 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. Commented Sep 15, 2022 at 13:13
  • Could you please give a code demo? Commented Sep 15, 2022 at 13:14
  • Refer to how to ask where the first step is to "search and then research" and you'll find plenty of related SO posts for this. Commented Sep 15, 2022 at 13:15
  • And if your introductory book doesn't explain how to write default constructors, get a better one Commented Sep 15, 2022 at 13:16

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.