How do I implement a random value in a method using pointers..

I'm working with classes, methods, objects. The .h & .cpp file.
In my h file i have dynamic attributes called.
1
2
3
4
5
class AtkBlob {
private:
int *hp, *attack, defense*, *speed;
string * name;
};

I have an initialize function in my cpp with parameters: (int h, int a, int d, int s, string n)
He wants me to assign .....
HP: in a range of 13 to 17. Attack: 5 to 8. He said I should perform these fixed stats in the initialize method for the class. All by using the formula:
 
rand () % (maxVal - minVal + 1) + minVal


How do I implement that into what I currently have?
1
2
3
void AtkBlob::initialize(int h, int a, int d, int s, string n) {
HP = new int();
}


Sorry I hope this makes sense, this is what I came up with? I thought I was supposed to have it listed as "hp = new(int);" rather than using the actual *. Struggling to know the difference.

1
2
3
void AtkBlob::initialize(int h, int a, int d, int s, string n) {
*hp = rand() % (17 - 13 + 1) + 13; 
}
Last edited on
to get 13-17 just add rand()%5+13, just as he said.
to deal with a pointer..
pointer = new type;
*pointer = rand()%5+13; //whatever values for whatever data item

and your destructor has to free them:
delete pointer;

p = new int; //get memory. a pointer has to point to memory to use it.
*p = 10; //use it. put 10 in the memory you got above.
delete p; // return the memory to the computer when finished.

think of pointers as an array index.
if you had
int x[] = {1,2,3};
int y; //this is like a pointer in this example.
cout << x[y]; // this is like using a pointer that you did not new or assign. bad: what is y's value? its not set! you are likely out of bounds!
y = 1; //this is like the new statement for a pointer
cout<<x[y];//OK, we know that y is 1 and that x[1] is 2
its just like that except x is computer ram and you need different syntax to express this.
Last edited on
@caiitys,

A couple of things unrelated to your question.

First, your defense variable is defined incorrectly. I always declare each variable on a separate line to make it easier to see syntax errors. Compare these 2:

1
2
3
int *hp, *attack, defense*, *speed;
string * name;
};


1
2
3
4
5
6
int *hp;
int *attack;
int defense*;
int *speed;
string * name;
};


Isn't it easier to see the error when the declaration is on a line by itself?

Second, this looks like a homework assignment where the teacher is having you learn how to allocate and deallocate dynamic memory. If so, so be it, and ignore the following.

However, from a typical perspective, this is a horrible design. One would almost never have pointers to dynamically allocated ints. The pointers are probably just as large as an int (so there is no space savings one is not allocated), and you don't have to remember to free the memory when destroying the AtkBlob object. Also, accessing the value is simpler because you don't need to dereference a pointer.
Topic archived. No new replies allowed.