using **Base to hold an array of Derived

Hi, my first post here! Trying to learn C++ by myself, as a hobby.

My question is: I know that converting a pointer **Derived to **Base does not work -- was reading from here :
[url] http://www.parashift.com/c++-faq-lite/proper-inheritance.html#faq-21.4 [\url]

but can I do the other way around (using an **Base to hold an array of Derived)?

For instance:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Foo { /* Stuff here */ };
class Bar:public Foo { /* Stuff here */ };
class Baz:public Foo { /* Stuff here */ };

int main()
{
   Foo **f;
   f=new Foo* [2];

   f[0]=new Bar;
   f[1]=new Baz;

return 0;
}


This code compiles, but can I be sure there will be no run-time errors, caused by something like the pointer arithmetic error described at the above link?

Thanks,
Roger
That's a tricky question. I think your example is exempt from the issue because your array is an array of pointers. Pointers will always be the same size. Their array was not of pointers but of varying-sized objects.

Regardless, in C++, you'd need to provide proof that you need to manage the array yourself rather than using an STL container. A vector< Foo * > is easier to manage and safer too.
Last edited on
Oh, and don't forget to delete the objects and delete[] the array!
Thanks for the reply.

A vector<Foo*> will do the job, was just curious if the Foo** is just ugly and should be avoided unless really necessary, or if it would be wrong.

Topic archived. No new replies allowed.