The * star/asterisk

The * pointer type

When the asterisk is to the left of a variable which is currently been declared, then the “*” is being used as part of the type to declare a new pointer.

Example with circle on the heap:

// Circle * means we are making a pointer to a Circle
Circle *ptr = new Circle(); 

Example with circle on the stack:

Circle c();

//Note this is using the & as an operator
Circle *ptr = &c

Example where circle is not initialized:

Circle *ptr = NULL;

The * dereference operator

When the asterisk is to the left of a variable which has already been declared, then the “*” is being used to get the actual object behind the address of the pointer.

Example of creating a new circle behind pointer:

Circle *ptr = NULL;
Circle c(); 

// Will call the Circle copy constructor
*ptr = c; 

Example of modifying a field behind pointer:

// Assuming Circle behind ptr was initialized
(*ptr).radius = 5;
// Equivalent to
ptr->radius = 5;

Example of copying entire circle behind pointer:

Circle c = *ptr;

Example of reading a field behind pointer:

// Assuming Circle behind ptr was initialized
int r1 = (*ptr).radius;
// Equivalent to
int r2 = ptr->radius

Example of calling a function behind pointer:

// Assuming Circle behind ptr was initialized
int d1 = (*ptr).getDiameter();
// Equivalent to
int d2 = ptr->getDiameter()

The & ampersand

The & reference type

When the ampersand is to the left of a variable which is currently being declared then the “&” is being used as part of the type to declare a new reference to the object.

Example with circle on the heap:

Circle *ptr = new Circle();

// Circle & means we are making a reference to a Circle
Circle &ref = *ptr;

Example with circle on the stack:

Circle c = Circle();
Circle &ref = c

The & address operator

When the ampersand is to the left of a variable which has already been declared then the “&” is being used to get the address of the object.

Example with circle on the stack:

Circle c;

// We are storing the address of the circle in ptr
Circle *ptr = &c;