Sab
Sab

Reputation: 533

Error in calling constructor

I tried to call a structure's constructor from a class constructor but its throwing an error. I have been trying to solve this for 30 mins

Structure:

struct node
{
    int val;
    node* left;
    node* right;
    node(int x)
    {
        val = x;
        left = NULL;
        right = NULL;
    }

    ~node()
    {
        delete(left);
        delete(right);
    }
};

class:

class Tree
{
    node* head;
    node list[1000];
    bool flag[1000] = {0};
public:
    Tree(int x)
    {
        head = new node(x);
    }

main() method:

int main()
{
    int a[] = {50,35,75,20,45,60,90,10,25,40,47,65,80,120,1,15,23,30,39,
46,49,82,110,21,24,48};
    Tree t(a[0]);

the error I am getting is

Error Log:

In constructor 'Tree::Tree(int)':|
|37|error: no matching function for call to 'node::node()'|
|37|note: candidates are:|
|17|note: node::node(int)|
|17|note:   candidate expects 1 argument, 0 provided|
|12|note: node::node(const node&)|
|12|note:   candidate expects 1 argument, 0 provided|

the structure constructor has one argument and in the class constructor I am calling with one argument yet the the error is throwing that the program call with 0 argument. I don't know where the problem is.

Thanks.

Upvotes: 1

Views: 129

Answers (2)

4pie0
4pie0

Reputation: 29724

node list[1000];

is an array of structures. A structure being element of the array needs a default constructor (or initializer has to be explicitly specified, see example), thus the error. Add a default constructor to node.


C++ Standard n3337 § 12.6.1/3

[ Note: If T is a class type with no default constructor, any declaration of an object of type T (or array thereof) is ill-formed if no initializer is explicitly specified (see 12.6 and 8.5). — end note ]

Upvotes: 5

Mike Seymour
Mike Seymour

Reputation: 254431

The Tree class contains nodes:

node list[1000];

which need to be default-initialised. But there's no default constructor to do that with.

Assuming you actually want a thousand nodes separate from the ones that make up the tree, You could make your existing constructor usable as a default constructor by giving it a default argument:

node(int x = 0)

or add a separate default constructor, for example:

node() : val(0), left(0), right(0) {}

or you might avoid the need for a default constructor by replacing the array with a more friendly container

std::vector<node> list;

and initialise that to the size you want in the constructor:

Tree(int x) : head(new node(x)), list(1000, node(0)) {}

Upvotes: 1

Related Questions