Storing Class object in a array

Please take a look at the following:
1
2
3
4
5
6
7
8
9
	dispenserType type[4];
    dispenserType appleJuice();
	type[0] = appleJuice;
    dispenserType orangeJuice();
	type[1] = orangeJuice;
    dispenserType mangoLassi();
	type[2] = mangoLassi;
    dispenserType fruitPunch();
	type[3] = fruitPunch;


as you can see i have stored different objects in the "type"Array.

The dispenserType class has a constructor that sets the number of items to 20.
so we have int variable numberfItems for the object appleJuice set to 20 so on and so forth.

The same class has also the following methods: method that decreases the numberOfItems by one:

1
2
3
4
5
6
7
8
9
void dispenserType::makeSale()
{
    numberOfItems--;
}
int dispenserType::getNoOfItems() const
{
    return numberOfItems;
}
 


If for example the following is called, appleJuice.makeSales, and subsequently, cout<< appleJuice.getNoOfItems() << endl;. the program would display the right numberOfItmes which is 19. On the other hand, if cout<<type[0].getNoOfItems()gets called, it would display the number 20.

That behavior leads me to think that appleJuice and type[0]are two separate objects.

My questions is, is there a way to create an array of objects without needing to declare an object and store in an array as I did it as I did?

thank you.
That behavior leads me to think that appleJuice and type[0]are two separate objects.
An alternative way of thinking about this is the store has items for sale. A purchaser puts items in a basket and take them to the checkout. Anyway, I appreciate that wan't the question.

is there a way to create an array of objects without needing to declare an object and store in an array as I did it If you work with objects direct, you have to declare them up front. That's because the compiler needs to know the size of the objects to begin with.

Object oriented programming is done in C++ using pointers. Typically pointers in a program have the same size, so you can get away with forward declaring objects.

For example:
1
2
3
4
5
class Item;

const size_t  MAXITEMS = 10;

Items* items[MAXITEMS];
Topic archived. No new replies allowed.