jeudi 27 août 2015

C++ wrong constructor being called

[I've been away from C++ for some time, so I expect that I'm doing something obviously wrong here.]

I expect the code below to print Test::Test(string,string,bool), however it prints Test::Test(string,bool). Why does it call the constructor that takes only one string parameter when two are provided? Surely a string can't be converted to a bool...? I have tried adding the explicit keyword but it does not help. Code is also at http://ift.tt/1KQoUq4.

#include <iostream>
#include <string>

using namespace std;

class Test
{
public:

    Test(const string& str1, bool flag=false)
    {
        cout << "Test::Test(string,bool)" << endl;
    }

    Test(const string& str1, const string& str2, bool flag=false)
    {
        cout << "Test::Test(string,string,bool)" << endl;
    }
};

int main()
{
    Test* test = new Test("foo", "bar");
}

Aucun commentaire:

Enregistrer un commentaire