To what use is multiple indirection in C++?

Tags: pointers c++

Under what circumstances might you want to use multiple indirection (that is, a chain of pointers as in Foo **) in C++?


Usually when you pass a pointer to a function as a return value:

ErrorCode AllocateObject (void **object);

where the function returns a success/failure error code and fills in the object parameter with a pointer to the new object:

*object = new Object;

This is used a lot in COM programming in Win32.

This is more of a C thing to do, in C++ you can often wrap this type of system into a class to make the code more readable.

By : Skizz

In C, the idiom is absolutely required. Consider the problem in which you want a function to add a string (pure C, so a char *) to an array of pointers to char *. The function prototype requires three levels of indirection:

int AddStringToList(unsigned int *count_ptr, char ***list_ptr, const char *string_to_add);

We call it as follows:

unsigned int   the_count = 0;
char         **the_list  = NULL;

AddStringToList(&the_count, &the_list, "The string I'm adding");

In C++ we have the option of using references instead, which would yield a different signature. But we still need the two levels of indirection you asked about in your original question:

int AddStringToList(unsigned int &count_ptr, char **&list_ptr, const char *string_to_add);
By : mlbrock

If you pass a pointer in as output parameter, you might want to pass it as Foo** and set its value as *ppFoo = pSomeOtherFoo.

And from the algorithms-and-data-structures department, you can use that double indirection to update pointers, which can be faster than for instance swapping actual objects.

This video can help you solving your question :)
By: admin