Can someone explain why the following works, Tried the following code and it works fine.
class A {
public :
int32_t temp ;
A ( bool y = false ) { }
} ;
int main ( int argc, char *argv[] )
{
A temp ;
temp = new A () ;
temp.temp = 5 ;
std::cout << " " << temp.temp << std::endl ;
return EXIT_SUCCESS;
} // ---------- end of function main ----------
In your case. The compiler used an implicitly defined Copy/Move Assignment operator. Which first constructs A with the pointer using your constructor that takes a bool.
All pointer types are implicitly convertible to bool in C++. There are two ways to prevent such nonsense:
explicit constructorsdeleted constructorsThus, you can do this:
class A {
public :
int32_t temp ;
explicit A( bool y = false ) {
}
//Additionally
A(void*) = delete;
};
defining a constructor that takes only a void* as deleted, will have overload resolution rank that constructor higher than the bool constructor when you pass a pointer. Since it will be picked by overload resolution whenever you pass a pointer and because it's deleted, the program will be ill-formed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With