Okay, example; imagine, you have a game which has a player which caries a rocket launcher. Rocket launcher's fire rate is let say, 20 rockets a second. Which means, at the same time you will have on screen defiantly more than one rocket. You have GUNS class and GUNSOBJECTS class. On guns class you have code something like
1 2 3
|
//Blah blah blah...
//Uhh! Player just shot a rocket!
GUNSOBJECTS[?]->spawnRocket();
|
The question mark is the problem. You cannot put in a static number, because the new rocket will keep replacing old rocket. You could put in a counter, but if you do that, you need to have separate function which would track statuses of GUNSOBJECTS classes and it would return a free instance number. Problem solved? Kinda. It would do the job, but the problem is - what if not only GUNS class wants to create a GUNOBJECT ? Maybe you have bot which also has a rocket launcher? Maybe rockets will be launched by the level? In all those cases you will have to drag that GUNOBJECTS instance tracker which is completely necessary. So, the better way would be to have additional class called GUNOBJECTSENCAPSULATED which would deal with appropriate instance calling and would also call certain functions.
So, now, with encapsulated ROCKETOBJECTS, whatever wants to fire a rocket, they would laterally need just to write a line of code such as
1 2 3
|
//Blah blah blah...
//Uhh! Player just shot a rocket!
GUNSOBJECTS->spawnRocket();
|
And that is it.
That is just simple example. There are way better ways to deal with such objects like having and objects manager and using the polymorphism and things like that.