lundi 30 janvier 2023

Constructor with arguments having default value equivalent to default constructor? [duplicate]

Will it be correct to say that constructor with argument default values equivalent to default constructor ?

The below program :

#include <iostream>

using namespace std;

class X
{
    int i;
    char ch;

public:
    X()
    {
        cout << "<" << __PRETTY_FUNCTION__ << "> :" << this << endl;
    }

    X(int ii = 0) : i(ii)
    {
        cout << "<" << __PRETTY_FUNCTION__ << "> :" << this << ", i=" << i << endl;
    }

    ~X() { cout << "X::~X()" << endl; }
};

void f()
{
    static int i;

    static X x1(47);
    static X x2;

}

int main(int argc, char *argv[])
{
    f();

    return 0;
} ///:~

refuses to compile if int ii =0. i.e., default value is provided to ii

StaticObjectsInFunctions.cpp:30:14: error: call of overloaded ‘X()’ is ambiguous
   30 |     static X x2;
      |              ^~
StaticObjectsInFunctions.cpp:17:5: note: candidate: ‘X::X(int)’
   17 |     X(int ii = 0) : i(ii)
      |     ^

Aucun commentaire:

Enregistrer un commentaire