I'm looking at what you mean when you create a cast constructor, which is theoretically a constructor that converts the parameter it receives into a new object other than the type of the .
The problem is that I don't understand this constructor very well. Could someone give me a clearer example? What I have found more or less is:
class B
{
public:
B(const C& d) {..}
//..
}
And it's still not clear to me, so is it a constructor that converts, for example, an integer into an object of, for example, character type?
Thanks and regards.
You have misunderstood. It is a constructor that allows you to convert a data type to the object you are programming; for instance:
The object
I
has a constructor that receivesint
, which means you can convert aint
to aI
:Or even pass integers to functions that receive a
I
:Maybe you were getting confused with the conversion operator, which allows your object to be converted to another data type:
Correct. Since it
I
has a constructor that takes aint
, it can be used to castint
toI
when callingfuncion(1, 2);
, this is called an " implicit cast ", because you are implicitly casting aint
toI
. If you make the conversion constructor ofint
toI
explicit, you ask the compiler not to do implicit conversions and as you pointed out: it will fail.