1

I am getting compilation issues for my code:

#include<iostream>

using namespace std;

struct TreeNode {
    int val;
    TreeNode *left, *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

int main(){
    pair <TreeNode, int> temp, node;
    return 0;
}

I can't overload the constructor of the structure which doesn't accept any value.

Error:

/usr/include/c++/4.6/bits/stl_pair.h:100:25: error: no matching function for call to ‘TreeNode::TreeNode()’
/usr/include/c++/4.6/bits/stl_pair.h:100:25: note: candidates are:
../a.cpp:18:2: note: TreeNode::TreeNode(int)
../a.cpp:18:2: note:   candidate expects 1 argument, 0 provided
../a.cpp:15:8: note: TreeNode::TreeNode(const TreeNode&)
../a.cpp:15:8: note:   candidate expects 1 argument, 0 provided
make: *** [102_binary-tree-level-order-traversal.o] Error 1

1 Answers1

1

Quick-Solution

Add the default-constructor to your code

struct TreeNode {
        int val;
        TreeNode *left, *right;
        TreeNode(){}    // DEFAULT CONSTRUCTOR
        TreeNode(int x) : val(x), left(NULL), right(NULL) {} //parameterized-constructor
};

int main(){
        pair <TreeNode, int> temp, node;  // Calls default constructor
        TreeNode t1;  // Calls default constructor
        TreeNode t2(100);  // Calls parameterized-constructor
        return 0;
}

Explanation:

When you don't specify any constructor inside the struct, there exists a default constructor defined implicitly. Hence, the below two definitions are logically equivalent.

Definition-1:

struct TreeNode {
        int val;
        TreeNode *left, *right;
};

Definition-2:

struct TreeNode {
        int val;
        TreeNode *left, *right;
        TreeNode(){}  // Default Constructor
};

When you specify a parameterized-constructor, the default constructor no more exists. So, you have to explicitly add a default-constructor(with no parameters)

The following statement(from your code) is calling the default constructor, which is no more present(as you have defined a default constructor). Hence you are getting the compile-time-error error: no matching function for call to ‘TreeNode::TreeNode()’

 pair <TreeNode, int> temp, 

You can fix it by adding a default constructor to your code as mentioned in the quick-solution.

Check it out: Does a c++ struct have a default constructor?

Community
  • 1
  • 1
Prabhakar
  • 41
  • 6