-1

So we say there is a base class A, and there are class B and class C that are inheritance of class A.

Now I want to create an array of pointers points to either B object or C object.

How can I do this?

andyz
  • 55
  • 10

1 Answers1

3

Pointers to a public base can point to objects derived of that base. Therefore you can do what you want like this:

A* arr[N];
eerorika
  • 232,697
  • 12
  • 197
  • 326
  • but think about this, if B has a member called num, then when I tried to do this:arr[0].num, it tells me that num is not a member of A. ? – andyz Mar 09 '16 at 20:06
  • @andyz correct. If you want to access the members of `B`, then you can convert the pointer to `B*`. – eerorika Mar 09 '16 at 20:13
  • ok. 1 more question. If I want to delete what arr[0] points to , should I do : delete arr[0]; arr[0]=NULL; or something else? – andyz Mar 09 '16 at 20:36
  • @andyz Does assigning a raw pointer to null delete the pointed object? The answer is no. For more info, read this: http://stackoverflow.com/a/9888542/2079303 – eerorika Mar 09 '16 at 20:54