Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to initialize the array-like member variable in the constructor?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
}

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading