below you can see that my constractor is giving my object a random number(which i can see when the program runs),
but once i call the aging() function the program writes a different number like
40567,54389, or another big number.
why is that?
#include <string>
#include <cstdlib>
#include <iostream>
usingnamespace std;
class rabbit
{
public:
rabbit(int r);
int aging();
protected:
int age;
int rabbitAge[10];
int b;
this is the rabbit.ccp
1 2 3 4 5 6 7 8 9
int b = r%10;
int rabbitAge[10] = {1,2,3,4,5,6,7,8,9,10};
int age = rabbitAge[b];
cout << "age "<<age<< endl;
int rabbit::aging(){
return age;
}
I assume this code is inside the rabbit constructor.
int age = rabbitAge[b];
This creates a local variable named age which is not the same as rabbit::age. If you want to assign the value to rabbit::age you should remove the int in front of the variable name.
You have the same problem with the other variables.
rabbit::rabbit( int r ) {
int b = r%10;
int rabbitAge[10] = {1,2,3,4,5,6,7,8,9,10};
this->age = rabbitAge[b];
}
// can be condensed to
rabbit::rabbit( int r ) {
this->age = 1 + (r%10);
}
// but one should rather use initializer list than assignment
rabbit::rabbit( int r )
: age( 1 + (r%10) )
{
}
Ok, I do admit that I did ignore the members rabbitAge and b. What is their true purpose?