If I have a class with a constructor like this:
class A {
public:
A(int e) {
// Use the `e` value
}
};
And if I make calls like this:
int main() {
A obj = 'c';
}
What conversions would take place? Would a conversion to type A
take place first, then how is it passed onto the constructor? Or would the character value be converted to int
?
Also which conversions here is blocked by declaring the constructor explicit?
To clarify my doubts:
If I declare the constructor as explicit
, I see these results:
int main() {
A objA = 'x'; // Error: conversion from ‘char’ to non-scalar type ‘A’ requested
A objA('x'); // OK
A objA = 1; // Error: conversion from ‘int’ to non-scalar type ‘A’ requested
A objA = A(1); // OK: Constructor called explicitly
A objA = (A)1; // OK: type Casting
}
I don't understand the behavior in the former three statements. Why do the first and third statements have conversion to A
type and not to int
in the first?
Why does the second statement compile even though there is an implicit conversion from char
to int
?