Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create c++ assignment operator for =0

In c++, a pointer type (void*/int*/char*) can be initialized with a value of 0 without type casting, but this doesn't work for any other value. Is it possible to instill the same behavior into a defined class? An =0 constructor, or an ==0 comparator? For clarification, I'm attempting to add syntax such that my n-dimensional vector class can be assigned to a zero vector with vec<n> dir = 0

Edit: using void* as the type of a constructor argument does in fact work, is this the best way to achieve this though?

like image 462
TechNeko Avatar asked Apr 13 '26 04:04

TechNeko


2 Answers

There is an implicit conversion from literal 0 to nullptr, and the type of nullptr is nullptr_t.

Thus, the following works the way you want:

// Needed for nullptr_t
#include <cstddef> 

struct A
{
    A(std::nullptr_t) {}
};

int main()
{
    A a = 0;
}

Of course, this also means that A a = nullptr is valid, but perhaps you can live with that...

It's possible that you can accomplish this without the indirection through nullptr_t with some modern constexpr and template shenanigans.

like image 116
molbdnilo Avatar answered Apr 16 '26 04:04

molbdnilo


You can't make a constructor that accepts only the literal value 0. There are a couple of things that get close.

#include <cstddef>

class Foo
{
    Foo(); // Construct from nothing at all
    Foo(std::nullptr_t) // Construct from the null pointer value
};

Which are used respectively

Foo foo_default;
Foo foo_null = nullptr;

Because 0 is also a null pointer value, you can use the std::nullptr_t overload with that.

Foo foo_zero = 0; // calls Foo(std::nullptr_t)
like image 37
Caleth Avatar answered Apr 16 '26 03:04

Caleth



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!