CPW
CPW

Reputation: 189

How parameter type conversion in C++ operator works?

I am creating a new class VarDbl, which contains a few explicit constructors as well as a + operator:

class VarDbl {
    ...
    explicit VarDbl(double value, double uncertainty);
    explicit VarDbl(double value);
    explicit VarDbl(long long value) noexcept;
    explicit VarDbl(long value) noexcept : VarDbl((long long) value) {}
    explicit VarDbl(int value) noexcept : VarDbl((long long) value) {}
    ...
    VarDbl operator+(const VarDbl other) const;
    ...
};

Because this class is easy to copy, I use const VarDbl other instead of the reference.

I am trying to test the implementation with the following code:

    VarDbl v1(1, sqrt(2));
    VarDbl v = v1 + 2;

gcc complains on the last line as:

no match for 'operator+' (operand types are 'VarDbl' and 'int')
[{
    "resource": "/c:/Users/Cheng/OneDrive/Documents/Proj/VarianceArithemtic/Cpp/TestVarDbl.cpp",
    "owner": "makefile-tools",
    "severity": 8,
    "message": "no match for 'operator+' (operand types are 'VarDbl' and 'int')",
    "source": "gcc",
    "startLineNumber": 185,
    "startColumn": 19,
    "endLineNumber": 185,
    "endColumn": 19
}]

From https://en.cppreference.com/w/cpp/language/implicit_conversion, it seems that int should be converted to VarDbl by using the explicit VarDbl(int value) constructor to create a temporary copy, but it does not happen.

Why?

Upvotes: 0

Views: 42

Answers (1)

John Zwinck
John Zwinck

Reputation: 249434

explicit constructors are not implicitly invoked. You need to remove explicit if you want them to be used automatically like that.

Upvotes: 1

Related Questions