I can't be bothered to write a complete explanation of classes (FWIW, I'm unlikely to create any value), but maybe I can help clarifying some things given that the example you posted isn't very good.
Nobody ever seems to explain what a
class actually is. Specifically, It's a
definition (in the mathematical sense) of a set of things. In a rough sense, the word "class" means "category": when you write a class, you're defining a particular category. Maybe you prefer the word "type", which again can be used in a type-theoretic sense, but also as a common sense "type of thing".
Intuitively, a class describes a "kind of thing".
The example you posted could be improved. Here's another (hopefully better) example.
1 2 3 4
|
class Person {
public:
string name;
};
|
This says, quite simply: "Every person has a name." Since
Person
is a
type in the same sense that
int
is a type,
you can create variables (called instances or objects of type Person
) that represent a Person:
Person person1;
And you can set person1's name:
person1.name = "Bob";
The class is contrived, but if the type
int
allows you to directly represent integers, then the type
Person
allows you to directly represent people in your program. This is the purpose of classes.
A class should represent a specific thing. This implies that every class name should be a noun*, and almost always singular. Name it something specific: calling it myClass
is a terrible choice, because nobody knows what a "myClass" is.
The key is making sure that your class
directly represents what it says in the name. Any object of type Person should always represent exactly one person. If a Person can do something, create a function which
tells them to do it.
Note:
Q: Where's the
member functions getName and setName in class Person?
A: They're gone, because you can just write person1.name (assuming it's public) instead of having to write two functions which do nothing. You should prefer not to add that boilerplate**.
Consider following the tutorial sequence on this site, specifically these two and beyond:
http://www.cplusplus.com/doc/tutorial/structures/
http://www.cplusplus.com/doc/tutorial/classes/
but the rest of the tutorial isn't bad either.
Feel free to ask if you have questions about anything I wrote here or any specifics.
* Some advanced techniques will use classes and objects with verbal names. You will know when you need to leave the guideline.
** The reason for adding that boilerplate is to add flexibility to the implementation of classes. The decision is a trade-off between additional boilerplate and flexibility. The goal of flexibility is to make changing your program simpler and less error-prone.
P.S.:
Perhaps you should leave that tutorial behind.
I clicked around and found this:
1 2 3 4 5 6
|
class BankAccount {
public:
void sayHi() {
cout << "Hi" << endl;
}
};
|
I didn't know that bank accounts could speak. No wonder you're finding this confusing ;)