5

My apologies if this is a dupe. I found a number of posts re. preventing implicit conversions, but nothing re. encouraging implicit constructions.

If I have:

class Rect
{
public:
    Rect( float x1, float y1, float x2, float y2){};
};

and the free function:

Rect Scale( const Rect & );

why would

Rect s = Scale( 137.0f, 68.0f, 235.0f, 156.0f );

not do an implicit construction of a const Rect& and instead generate this compiler error

'Scale' : function does not take 4 arguments
BeeBand
  • 10,953
  • 19
  • 61
  • 83

4 Answers4

11

Because the language does not support this feature. You have to write

Rect s = Scale(Rect(137.0f, 68.0f, 235.0f, 156.0f));
SebastianK
  • 3,582
  • 3
  • 30
  • 48
7

"Conversions" in C++ are between objects of one type and another type. You have 4 objects (all of type float), so you could have 4 conversions to 4 other types. There's no way to convert (in the C++ sense of the word) 4 objects to one object.

MSalters
  • 173,980
  • 10
  • 155
  • 350
3

An implicit conversion via constructor takes place if and only if the constructor takes exactly 1 argument and isn't declared explicit. In this case it takes 4, thus the result.

Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
2

I think you're talking about implicitly constructing an object. For instance,

class IntWrapper {
    public:
        IntWrapper(int x) { }
};

void DoSomething( const IntWrapper& ) { }

int main() {
    DoSomething(5);
}

This works because IntWrapper's constructor takes only one argument. In your case, Rect needs 4 arguments, so there's no implicit construction.

Pedro d'Aquino
  • 5,130
  • 6
  • 36
  • 46
  • Check out this question on `explicit`, which is the way you forbid this behavior: http://stackoverflow.com/questions/121162/what-does-the-explicit-keyword-in-c-mean – Pedro d'Aquino Nov 05 '10 at 12:23