Why store variables inside classes?

What is the use of storing variables inside classes?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>
using namespace std;

class theClass{
	public:
		void setName(string x){
			name = x;
		}
		
		string getName(){
			return name;
		}
	private:
		string name;
};

int main()
{
	theClass theObject;

	theObject.setName("Sir CodeALot");
	cout << theObject.getName() << endl;	
}
In your example it makes very little difference. If anything the class is unnecessary because it just makes extra work to access the contained string.

The thing to understand about classes is that they represent a "thing". The variables they contain will all be part of describing that "thing".

A more practical example would be a class which represents an enemy in a RPG style video game:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Enemy
{
private:
  int hp;   // current hp
  int maxhp;  // max hp
  int strength;  // strength

public:
  // a function called when the Enemy has to choose an action
  Action GetAction()
  {
    if((hp * 4) < maxhp)  // if we have less than 25% hp
    {
      return Action("Run Away");  // try to run away
    }

    // otherwise, pick an attack at random
    if((rand() % 8) != 0)
    {
      return Action( "Normal Attack", strength );
    }
    else
    {
      return Action( "Super Special Move", strength * 2 );
    }
  }
};
I suppose you weren't aware that you can create an arbitrary number of class instances and that each instance has its own copy of that variable, otherwise your question would make little sense.
Athar: Do you mean I can use the same class and give it another object and that object will have it's own set of variables?
Sort of. You don't give an object a class. An object is an instance of a class.
But your understanding is correct: each Object of a class has its own variables. Two Enemy objects will all have their own hp, maxhp & strength.
I think i got a quite good understanding of it now. Thanks!
Topic archived. No new replies allowed.