2

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?

2
  • It's called polymorphism. Construct a base class (e.g. Vehicle), and various subclasses (e.g. Car, Bus). Then, you can store all Cars and Buses in a Vehicle container using the power of smart pointers. I asked something similar here. Commented Dec 10, 2014 at 16:35
  • Suggestion, add a code example Commented Dec 10, 2014 at 19:56

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.