Reputation: 11558
I have few classes
class A;
class B;
class C;
class D;
Classes B,C,D inherits from A. In my problem i have multiple classes B,C,D and each of them have a static field for example
static int gold;
Class A is abstract class and it have method getGold();
Of course every class B,C,D has its own static field
static int gold;
and in every class (B,C,D) i implement in the same way
getGold()
{
return gold;
}
It's copy & paste but i don't have idea how make it better.
B,C,D for example
Every object of the same class costs the same so this is why i want to have only one int Of course this is only example instead int i can have there for example class Gold instance :)
Upvotes: 2
Views: 98
Reputation: 275220
If it does not need to vary, use an enum for the value.
Regardless, return gold is not a bad idea. If it was more complex, you might use the CRTP. A helper template the inherits from A and implements get gold.
You pass B in as a template parameter and then inherit B from it. The methods of the template can static cast this to a B and use B's state.
CRTP is pretty easy to Google.
Remember, return gold is probably best.
Upvotes: 1