Reputation: 789
void Foo::Bar(Baz& x)
{
z = &x;
}
Foo* foo;
foo -> Bar(nullptr);
I'm trying to create a generic template, Baz, using just typedef. Since z is private and belongs to Foo, I have trouble assigning nullptr to z.
If possible, I'd like the best way to set z to a nullptr without changing too much of the implementation-- unless this is that bad of an implementation.
I was thinking maybe
(Baz *) 0, or *(void * )0 or the Nullable Class .
Upvotes: 1
Views: 11419
Reputation: 5336
If you do want to keep this method:
void Foo::Bar(Baz& x)
{
z = &x;
}
But still want to be able to set z
as nullptr
, you can add an overload for Bar
that specifically takes a nullptr
argument:
void Foo::Bar(std::nullptr_t nullp)
{
z = nullp;
}
Upvotes: 8
Reputation: 111
void Foo::Bar(Baz* x)
{
z = x;
}
Foo* foo;
Baz* ptr = NULL;
foo -> Bar(ptr);
Upvotes: 0
Reputation: 10667
nullptr
is a pointer, not a valid reference:
int &v = nullptr;
The gcc complains:
bla.cpp:1:10: error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘std::nullptr_t’
int &v = nullptr;
So you can't pass it as a reference argument. If you want to be able to pass it change x
to be a (possibly const) pointer:
void Foo::Bar(Baz* const x) {
z = x;
}
Upvotes: 1
Reputation: 45410
If you want Foo::Bar
to take nullptr, you need to change parameter to pointer type:
void Foo::Bar(Baz* x)
{
z = x;
}
Foo* foo = new Foo();
foo -> Bar(nullptr);
Note: you need to allocate object for foo pointer
before using it, otherwise behavior is undefined.
Upvotes: 3