C++ call of overloaded constructor is ambiguous

grd picture grd · Oct 22, 2016 · Viewed 10.2k times · Source

Let's say I have this dummy class definition:

    class Node
    {
    public:
        Node ();
        Node (const int = 0);
        int getVal();
    private:
        int val;
    };

And dummy constructor implementations for educational purposes only as well:

Node::Node () : val(-1)
{
    cout << "Node:: DEFAULT CONSTRUCTOR" << endl;
}


Node::Node(const int v) : val(v) 
{
    cout << "Node:: CONV CONSTRUCTOR val=" << v << endl;
}    

Now, if I compile (with options: -Wall -Weffc++ -std=c++11) the code below:

#include <iostream>
#include "node.h"
using namespace std;

int main()
{   
    Node n;
    return 0;
}

I get this error, and does not compile at all:

node_client.CPP: In function ‘int main()’:
node_client.CPP:10:16: error: call of overloaded ‘Node()’ is ambiguous
  Node n;  
                ^
node_client.CPP:10:16: note: candidates are:
In file included from node_client.CPP:4:0:
node.h:14:5: note: Node::Node(int)
     Node (const int = 0);     
     ^
node.h:13:2: note: Node::Node()
  Node ();
  ^

I cannot understand why.

As far as I know (I am learning C++), a call to Node::Node() should not be ambiguous with respect to Node::Node(const int) because the have a different parameter signature.

There is something I am missing: What it is?

Answer

πάντα ῥεῖ picture πάντα ῥεῖ · Oct 22, 2016

a call to Node::Node() should not be ambiguous with respect to Node::Node(const int) because the have a different parameter signature.

Sure that is ambiguous. Think twice!

You have

    Node ();
    Node (const int = 0);

which one should be selected when you call Node()?? The one with the defaulted value parameter?

It should work without providing the default:

    Node ();
    Node (const int); // <<<<<<<<<<<<< No default