Don't have it be static. For example:
#include <iostream>
class Weapon {
public:
Weapon();
virtual int Rate();
virtual void Rate(int r);
protected:
int rate;
};
Weapon::Weapon() {
rate = 10;
}
class Minigun : public Weapon {
public:
Minigun();
};
Minigun::Minigun() {
rate = 30;
}
int Weapon::Rate() {
return rate;
}
void Weapon::Rate(int r) {
rate = r;
}
int main() {
Minigun ThisGun;
Weapon AnyGun;
std::cout << ThisGun.Rate() << std::endl;
std::cout << AnyGun.Rate() << std::endl;
AnyGun.Rate(15);
std::cout << AnyGun.Rate() << std::endl;
return 0;
}
We declare a protected int in the base class. This means any derived class that inherits the base class will have that variable as well. You only declare a variable static
if you want only one instance of that variable shared for all instances of that object.
Base constructors will get called before the derived constructor. You can reset default values in your derived constructor for objects of that specific type. Public functions will call the most derived virtual function. In this case, we want Minigun
to behave the same for our rate functions so we simple do not implement any function for Minigun
so the Weapon
functions are called instead.
output is:
30
10
15