C++ union equality

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • hype261
    New Member
    • Apr 2010
    • 207

    C++ union equality

    I don't have a C++ compiler with me right now and can't find an answer on the net and I keep on going back and forth in my head on whether this would be legal or not.

    So here is my struct in question...

    Code:
    struct WorldProperty
    {
    WORLD_PROP_KEY eKey;
    
    	union value
    	{
    		bool bValue;
    		float fValue;
    		int nValue;
    	};
    
    	bool operator==(const WorldProperty & rhs) const{return eKey == rhs.eKey && value == value;};
    };
    So my WORLD_PROP_KEY is an enumeration which tracks which World Property this struct is associated with. My question is will the equality operator work?
  • donbock
    Recognized Expert Top Contributor
    • Mar 2008
    • 2427

    #2
    I don't know anything about C++, so be skeptical about my comments.

    The members of the value union are all different sizes. Suppose you want to compare two structures that both happen to contain bool values. Wouldn't you want the structures to compare as equal if eKey and value.bValue matched, regardless of whether the unused padding in value were different?

    Comment

    • hype261
      New Member
      • Apr 2010
      • 207

      #3
      Donbock,

      That is true, but at run time I won't know what type of information is stored in the union when I do my comparisons. I suppose I could make another enum to track which type got written to, but in that case I probably should make this a class with getters and setters.

      Comment

      • Banfa
        Recognized Expert Expert
        • Feb 2006
        • 9067

        #4
        I tried your code, it doesn't compile (gcc 4.4.0) it gives

        bytes.cpp: In member function 'bool WorldProperty:: operator==(cons t WorldProperty&) const':
        bytes.cpp:13: error: expected primary-expression before '==' token
        bytes.cpp:13: error: expected primary-expression before ';' token

        Because value is not an expression, it has no value, and so is not comparable.

        Comment

        • hype261
          New Member
          • Apr 2010
          • 207

          #5
          Banfa,

          Thanks for trying it out. I ended up doing another enum to track which type of data is loaded into the struct so I can do the comparison correctly.

          Comment

          Working...