object variable does not stay the same, why?

Write your question here.

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?




this is the main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include "rabbit.h"
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;

int main(){
srand(time(0));
rabbit ro1(rand());
cout << ro1.aging();
}


this is the "rabbit.h"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
 #include <string>
#include <cstdlib>
#include <iostream>
using namespace 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;
}

Both your rabbit.h and rabbit.cpp look incomplete.
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.
yes it works fine now, thank you.
Overall, the
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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?
Topic archived. No new replies allowed.