3

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  ----------
WhiZTiM
  • 21,207
  • 4
  • 43
  • 68

1 Answers1

7

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 constructors
  • deleted constructors

Thus, 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.

Community
  • 1
  • 1
WhiZTiM
  • 21,207
  • 4
  • 43
  • 68