Beginning game classes

I'll get right to the point:
I'm trying to make a game sort of like Dwarf Fortress, but a lot less complex. It's going to be text based, and you'd enter in text commands, and the dwarves would do it. I've never really used classes much, so is there anything wrong with what I have below?

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
28
class Dwarf
{
    int age, Xpos, Ypos, carry;
    string job;
    
    public:
    Dwarf (int, int, int);
    ~Dwarf ();
};

Dwarf::Dwarf (int a, int x, int y) 
{
  age = new int;
  Xpos = new int;
  Ypost = new int;
  *age = a;
  *Xpos = x;
  *Ypos = y;
}

Dwarf::~Dwarf()
 {
  delete age;
  delete job;
  delete Xpos;
  delete Ypos;
  delete carry;
};
Last edited on
Your age, Xpos and Ypos variables aren't pointers, so you can't assign them like that. Nor can I think of why you'd need to.

Keep it simple. :-)

1
2
3
4
5
6
Dwarf::Dwarf( int a, int x, int y )
{
   age = a;
   Xpos = x;
   Ypos = y;
}
I'm getting an error for my deconstructer function:

23|error: type 'int' argument given to 'delete', expected pointer|
24|error: type 'std::string {aka struct std::basic_string<char>}' argument given to 'delete', expected pointer|

etc.
That's because you are trying to call delete on a regular int. Remove the delete statements in the destructor.

So... Should anything go in the deconstructor?
I still don't really understand. They deleted the array, but I shouldn't delete my ints?
You only use delete when you've used new to allocate memory.

Since you don't need to use new, as shown in my example, then you don't need to use delete.
Thanks! :)
How would I create multiple instances of the class? For example, if I wanted to add a number of dwarves in game, but I wouldn't know how many to create until I was playing.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Dwarf
{
    public:
    int age, Xpos, Ypos, carry;
    string job, name;
    Dwarf (string n, int a, int x, int y);
    ~Dwarf ();

    string GetName(){return name;}
    string GetJob(){return job;}
    int GetXpos(){return Xpos;}
    int GetYpos(){return Ypos;}
    int GetCarry(){return carry;}
};
You would use std::vector
http://www.cplusplus.com/vector
1
2
3
4
std::vector<Dwarf> dwarves;
//whenever you want to add another dwarf:
dwarves.push_back(Dwarf("Name", 10, 32, 24));
//in C++11 it is better to use .emplace_back() for this 
Last edited on
Okay, thanks! :) If I did that and created a vector, how would I call a Dwarf class function like GetName() for any individual dwarf? Could I do that?
They work like arrays. Just use the [] operator:

1
2
3
// 0 is the first dwarf in the vector, 1 is the next one, etc.

dwarves[0].GetName();  // gets the name of the first dwarf 


You can use dwarves.size(); to find out how many dwarves are in your vector.
Ah, thanks! :)
Topic archived. No new replies allowed.