Search code examples
c++arraysdouble-pointer

Using a "double-pointer" dynamic array in C++


Okay, so I have this assignment that I've gotten stuck on and I'd appriciate any help.

Basically what I have is a base-class and two classes that derive from that base class, which hasn't been a problem. But now I need to make a "container" class that has a "double-pointer" dynamic array containing instances of the two classes.

My problem is then: why does a double-pointer array help me here? This double-pointer business seems quite confusing to me. Through googling I've found out that a double-pointer basically is a pointer to a pointer, but how does that help me here and how do I declare a double-pointer dynamic array?

Also, how can I store two different classes(although deriving from the same base-class) in the same array, isn't this two different data-types?


Solution

  • You need one pointer to make it an array of objects that might be of any derived class -- all of the objects in an array must be the same static type, so you want an array of pointers to the base class. That way all elements of the array are the same (pointer) type, but any of them might point at any object of the base or any derived class.

    You need a second pointer to make it a dynamic array -- arrays in C/C++ are fixed size, so if you want to be able to change the size you need to use a pointer to an array of unspecified size (which is just a pointer).

    So you end up needing a pointer to a pointer (a double pointer) for your container.