Moberg
Moberg

Reputation: 5493

Implicit cast through constructor with multiple arguments

If I have these 2 constructors for MyClass:

MyClass(int n1);
MyClass(int n1, int n2);

and an overloaded (non-member) operator+:

MyClass operator+(MyClass m1, const MyClass& m2);

This enables me to write code like this:

MyClass m;
5 + m:

which I guess uses an implicit cast through the defined constructor, correct?

Is there any way to do this implicit cast with the constructor taking 2 arguments? With code looking something like this:

MyClass m;
{15, 8} + m:

?

Or maybe just do an explicit cast from {9, 4} to a MyClass object?

Upvotes: 0

Views: 297

Answers (3)

Bryan
Bryan

Reputation: 2128

I don't believe so, but why do you need it to be implicit rather than explicit? If you're going to have to use the bracket notation anyway, it's not something that could be generated from a single variable, so I don't believe there's any downside to simply saying:

myclass(15, 8) + m;

This will generate it on the stack, and produce the same result as an implicit cast.

Upvotes: 0

No, but you can construct in place:

MyClass m;
m + MyClass(15,8);

Upvotes: 1

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272467

In a word, no. The most succinct option is MyClass(15,8) + m;.

Upvotes: 5

Related Questions