Pass by pointer

Pass an object's address when the object may be optional.

Syntax

void reset(int* value)
{
	if (value == nullptr)
		return;

	*value = 0;
}

int count { 5 };
reset(&count);  // count is now 0
reset(nullptr); // no object

The pointer is copied into the parameter. Dereferencing it accesses the caller’s object.

When to use it

  • nullptr represents a valid absence of an object
  • The interface already works with pointers
  • The function must access or modify the pointed-to object

Use const T* when the pointed-to object is optional but read-only:

void print(const Widget* object);