I have a class containing union as a field. The union is of pointers to two different classes. As a second field my class contains a flag informing which type is currently stored.
class Item {
std::string *title;
bool who_am_I;
union { Submenu *smenu; Function *call; } content;
public:
bool am_I_a_submenu();
bool am_I_a_function();
Submenu *give_me_submenu();
Function *give_me_function();
/*(...)*/
};
Now, before each usage of my “give_me” methods I urge user to check the type through the appropriate method accessing the flag, i.e. the “am_I” methods. Nevertheless I would like my library to throw appropriate exception if the user would happen to forget about it. Can I do that without checking the flag inside the “give_me” method? I ask because it would mean that in normal usage the flag is unnecessarily checked twice.
I was wondering if, which and when does c++ throw some in build exception once the conflict of types will appear causing program malfunctioning. Or maybe should I handle this case otherwise, still preferably without double checking the flag.
OK, first of all… why do you care if the flag is checked twice? Is that really a serious performance bottleneck in your product that profiling has shown must be optimized? I very much doubt it.
But even if it is a performance bottleneck, what’s more important? A properly functioning application that doesn’t crash seems to me to be an acceptable tradeoff for a super-tiny amount of extra overhead.
But you should probably just redesign your interface(s) so that the user always knows what he has and can’t make mistakes like this.