I encountered a strange phenomenon when running the following code:
#include <iostream> class Piece { public: class Queen; class Knight; union Any; virtual const char* name() const = 0; }; class Piece::Queen : public Piece { public: virtual const char* name() const { return "Queen"; } }; class Piece::Knight : public Piece { public: virtual const char* name() const { return "Knight"; } }; union Piece::Any { public: Any() {} Piece::Queen queen; Piece::Knight knight; }; using namespace std; int main(int argc, const char* argv[]) { Piece::Any any; any.queen = Piece::Queen(); cout << any.queen.name() << endl; return 0; }
The program was compiled in the Apple LLVM 3.0 compiler, but the output was Knight. I expected the output to be "Queen." From my testing, I saw that when Piece :: Any constructor works by default, it calls the Piece :: Queen and Piece :: Knights constructs, one after the other. If I were to declare Piece :: Any like this:
union Piece::Any { public: Any() {} Piece::Knight knight; Piece::Queen queen; };
(I basically changed the order of the knight and queen), then the exit will be the queen. Any help would be appreciated.
thanks
source share