Zell Faze Zell Faze - 1 year ago 83
C++ Question

Class method masquerading as field

I have a class named ResourceBin.

class ResourceBin
virtual ~ResourceBin();
int getResource(Resources resource) const;
void setResource(Resources resource, int amount);
int addResource(Resources resource, int amount);
unsigned int getMax(Resources resource) const;
void setMax(Resources resource, unsigned int amount);
bool simulateAddResource(Resources resource, int amount) const;
bool maxOn = true;
ResourceBin operator+(const ResourceBin& bin);
int resources[2];
unsigned int maxamount[2];
unsigned int getIndex(Resources resource) const;

typedef ResourceBin ResourceList;

I would like to make sure that if MaxOn is equal to true that none of my resource values (stored in resources) is greater than it's max amount. Is there any way that I can make a method run anytime that maxOn is changed or set?

Answer Source

The short answer is: practically no. You have to make maxOn a private class member, and provide its own getter and setter method.

The reason for the "practically" qualifier is that it's possible to build a house of cards which will result in a statement of the form:


execute a class method. maxOn wouldn't be an ordinary bool, but a custom class, with an operator= and an operator bool(), making it act like a bool value, but the operator= would update the flag, and, using a number of approaches, execute a method in its parent class to validate the required constraint.

It's possible, and it's quite a bit of work. But don't do that. It's ugly. Just replace maxOn with a getter and a setter.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download