In my program, I have a class with two subclasses. The superclass has a function that adds the value of its two private member variables and assigns it to a protected member variable with the use of a public member function. That variable is then used to assign its value to a member variable of one of the subclasses in another function, like so:
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 29
|
class Foo
{
public:
void fooFunct();
protected:
int protVar;
private:
int priVar1, priVar2;
};
void Foo::fooFunct()
{
fooVar1 = rand() % 6 + 1;
fooVar2 = rand() % 6 + 1;
protVar = fooVar1 + fooVar2;
}
class Bar: public Foo
{
public:
void barFunct();
private:
int barVar;
};
void Bar::barFunct()
{
barVar = protVar;
}
|
Here's the deal. When a Bar class object is created, its constructor will call fooFunct() first, and barFunct() after. fooFunct seems to work just fine, I've checked the variables by cout'ing them and they show all the correct values. However, when I useprotVar in barFunct(), it somehow changes value so that it always has the value 9.
Is there something I am not thinking about? It can't be the rand() functions because the value 9 is displayed every time I rebuild and rerun the program, and I always have the console print out the values of fooVar1, fooVar2 and protVar after they're used in fooFunct(). The only thing I can see as the reason is if protVar becomes a "different variable" when used by a function of a Bar class object. As in, I would have to explicitly call protVar from the Foo class object by doing something like this:
aFooObject.get_protVar();
So the question is, why is protVar acting up?