array of pointers to derived class

Hi

I have a class called 'base', and a derived class called 'sub'.

What i can do:
1
2
3
4
sub s;
base b = s;

base *p = new sub[3]


What i can't do is assign a sub** to a base** variable:
base **pp = new sub*[4];

Why is that the case?

Thanks
Jody
A sub is a base, therefore a base* can point to a sub.

However a sub* is not a base*, therefore a base** cannot point to a sub*. This leads to potential screwups:

Consider the following situation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class base { };
class sub1 : public base { void Foo(); }; // note:  Foo exists only for sub1
class sub2 : public base { };  // no Foo for sub2

int main()
{
  sub1* p1 = new sub1;
  sub2* p2 = new sub2;

  base** p = &p1;  // fortunately this is a compiler error.  However... if it wasn't...

  *p = p2; // p1 now == p2

  p1->Foo();  // tries to call Foo() with a sub1 object, but actually has a sub2 object!
  //  EXPLODE
}
Last edited on
You could create it as
base **pp = new base*[4];
and still store pointers to sub objects in it.
pp[0][0] = new sub;
base *p = new sub[3]; Don't do that.
Think what p[1] is.
Good catch, ne555. I totally missed that.
Topic archived. No new replies allowed.