2

I have a fruit class and a apple which inherits from the fruits. Lets say i have an array of individual sorts of fruits. I could say apples, bananas and other fruits.
The problem: When i try to get the values from an element of that array (a child of fruit) it won't compile.

class Fruit{
public: 
    Fruit();
}

class Apple : public Fruit{
public: 
    Apple();
    int count; //number of apples in the store
}

int main(){
    Fruit market[3];
    market[0] = Apple();

    int apples = market[0].count;
}

I know that this is because the program doesn't know that it is looking at an apple; But if i certainly know that it is an apple (through checking for example), how can i access Apple.count?

GRASBOCK
  • 631
  • 6
  • 16

2 Answers2

8

You can't do this. An array is a linear bunch of bytes which store one object adjacent to the next. They all have to have the same size, therefore. Since an Apple doesn't fit in the space taken by a Fruit, you can't store an Apple in an array slot meant for a Fruit.

What you can do is store an array of pointers. That's the usual solution for keeping polymorphic types:

std::array<Fruit*, 3> market;
market[0] = new Apple();
// ...
delete market[0];

Since pointers generally have a single size within one program, storing disparate types via pointers is sensible. You can also use C++ "smart pointers," like so:

std::array<std::unique_ptr<Fruit>, 3> market;
market[0].reset(new Apple());
// ...
// delete is called automatically

Now if you need to access count you have two choices. If you are certain that market[0] is an Apple, you can use this:

static_cast<Apple&>(market[0]).count

If you are not sure, you can check:

if (Apple* apple = dynamic_cast<Apple*>(&market[0])) {
    // use apple->count
} else {
    // it's not an Apple
}
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • plus to access the child methods, variables you will need to cast the pointer than. – MagunRa Dec 18 '15 at 15:45
  • Thanks that part with the downcasting really gave me some insight into user defined casting... really never knew about that possibility! Opens a Gate for me :D – GRASBOCK Dec 18 '15 at 17:14
0

but if not every fruit has a count (the market is a bad example here) – RIJIK 25 secs ago

Then you're out of luck. You need to downcast. And change to some form of reference semantics.

Bartek Banachewicz
  • 38,596
  • 7
  • 91
  • 135