Tony Tarng
Tony Tarng

Reputation: 749

Implicit conversion from int to a class type

I ran across some code that looked like this:

class Cents
{
private:
    int m_nCents;
public:
    Cents(int nCents) : m_nCents(nCents)
    {
    }
 };

int main(){
    Cents c = 0; // why is this possible?
}

Why is it possible to convert from int to type of class Cents? Also, is the copy constructor called in this case?

Upvotes: 0

Views: 522

Answers (1)

edmz
edmz

Reputation: 8494

Why is it possible to convert from int to type of class Cents?

It is allowed because it's handy sometimes. But it may also be problematic: that's why you can forbid such implicit constructions by making the class constructor explicit.

Also, is the copy constructor called in this case?

Since it's an rvalue, the call would be to a move constructor/assignment (which could fallback to a copy ctor/assignment); but the compiler will likely omit that. If you wrote that explicitly, it would be equivalent to:

Cents c = Cents(0); 

Upvotes: 1

Related Questions