A lazy software engineer was recently browsing over the source code in his company's code repository (Because he was bored of reading puzzles on Puzzling.SE) when he found the following source code:
class Egg {
public:
Egg() : hatched_{ false } { }
bool hatched() { return hatched_; }
protected:
Egg(bool hatched) : hatched_{ hatched } { }
private:
bool hatched_;
};
struct Chicken : public Egg {
Chicken() : Egg{ true } { }
};
void count(Egg* (&eggs)[5]) {
for (const auto& egg : eggs)
if (!egg->hatched())
throw "Exception";
}
void hatch(Egg*& egg) {
delete egg;
egg = new Chicken;
}
int main() {
Egg* eggs[5];
for (auto& egg : eggs)
egg = new Egg;
hatch(eggs[0]);
// count(eggs);
hatch(eggs[1]);
hatch(eggs[2]);
hatch(eggs[3]);
// count(eggs);
hatch(eggs[4]);
count(eggs);
for (const auto& egg : eggs) // Resources cleaned up!
delete egg;
}
Looking over the source code, the lazy engineer couldn't find anything meaningful. Running the code produced no output. The only (shocking) thing he noticed was the memory leak in the case of the thrown exception (Someone needs to teach this guy RAII)
What phrase does the source code above represent?
Very Big Hint:
The phrase is a (fairly common) idiom.
Answer
The phrase is:
Don't count your chickens before they're hatched
Because
The
hatch
function turns an Egg into a Chicken. The user has an array of eggs but hatches all of them before counting the chickens. It looks like he tried counting them before they were hatched (resulting in the exception which prevented him from doing that) so he commented those out. Finally he was able to count them after they had all been hatched.
No comments:
Post a Comment