Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion From Pointer To NonScalar Object Type?

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  ----------
like image 456
Ravi Parikh Avatar asked Jul 06 '26 19:07

Ravi Parikh


1 Answers

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.

like image 194
WhiZTiM Avatar answered Jul 08 '26 10:07

WhiZTiM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!