Hi there,
The main benefit of Object Oriented Design (that is, designing a program using classes) is that you can model your program towards real life creating separate components and that these components.
In practice, let's consider a game, like pacman.
If you would describe pacman to someone, you could say "pacman is a game where you move around a figure, which eats up dots, fruits and keeps away from ghosts".
In object oriented design, we would analyse that as the following:
- Figure pacman which moves and eats things
- Eaten things: dots, fruits, ghosts
(note that for clarity I'm leaving out the actual game grid)
We can then transfer this into classes:
Class PacMan:
move();
eat(Thing);
Class Thing:
score;
lives;
Class Dot is a Thing:
score +1;
lives remain the same;
Class Fruit is a Thing:
score +10;
lives +1;
Class Ghost is a Thing:
score -10;
lives -1;
|
Keep in mind that this is just a rough example.
The benefit is that when you would like to add a "thing", it's easy to do, when you want to change the score added by eating a dot, it's easy to do. That is because every class forms a seperate entity, with a limited interface to the outside. Think of it as going to the cash register of a store. You pay the person at the register, but don't care what happens after that, things like increasing the daily income of the store, updating the stock, etc., you simply use the interface the cash register provides you. Similarly, classes cooperate with one and other through the interface they present to one and other, which means that the details of implementation are hidden and known only to a class itself.
It's also worth mentioning that C++ actually uses a lot of classes in it's standard library. Take std::string for instance. That is actually a class, and every std::string you create is an object of that class. So you can't really go about using C++ not using classes (unless you confine yourself to the C-subset, in which case, just learn C).
If you don't see a constructor defined for a class, the default constructor will just be called.
The default constructor is code generated by the compiler, but which doesn't really alter anything to the object you're creating.
So to conclude, the use of classes
may benefit the clearness of your design, the maintainability of your code and make your code more reusable (you can reuse classes you created before easily).
I say
may, because it depends on how you use it, it could also clutter your code into a mess if you don't know what you're doing.
If you want a good read on this stuff, have a look at Robert Lafore's Object Oriented programming using C++.
Hope that helps.
All the best,
NwN
Edit: I'm so slow... sorry!