Thread: How Can An Entire Object be Compared to a Single Constant?

  1. #1
    Set Apart -- jrahhali's Avatar
    Join Date
    Nov 2002
    Posts
    256

    How Can An Entire Object be Compared to a Single Constant?

    This question actually originates from a Visual Basic course I'm taking, but I think it can be answered here.

    Code:
    Dim WhichButtonDialogResult As DialogResult
    
    WhichButtonDialogResult = MessageBox.Show(bunch of arguments with Yes and No buttons)
    
    If WhichButtonDialogResult = DialogResult.Yes Then
       'Code...
    EndIf
    DialogResult is an object that MessageBox returns when the user clicks the yes or no button.

    This is my question (referring to the code in red). If objects have both methods and properties, then how can you simply test if a constant (DialogResult.Yes) is equal to the entire object?

    I would expect something like

    Code:
    If WhichButtonDialogResult.Result = DialogResult.Yes
    Instead.
    Clear the mines from our Shazbot!
    Get the enemy Shazbot!

  2. #2
    Registered User MacNilly's Avatar
    Join Date
    Oct 2005
    Location
    CA, USA
    Posts
    466
    You could overload a operator== class method for the class you want to compare for each type you want to compare it to.

    I don't know what type DialogResult.Yes is, but say it's an integer constant, defined in the DialogResult class.

    For example,

    Code:
    class DialogResult
    {
    public:
        typedef enum { Yes, No } ResultType;
    
        // compares two DialogResults
        bool operator==(const DialogResult& rhs)
        {
            // compare this object with right hand side
        }
    
        // compares this DialogResult with a ResultType (Yes or No)
        bool operator==(ResultType n)
        {
            return (n == Yes);
        }
    };
    [EDIT] Corrected Code [/EDIT]

    You can overload operator== for as many types as you like, but note that the compiler won't force any semantics (meaning). In other words, you can overload operator== to do multiplication, but that is extremely poor practice.
    Last edited by MacNilly; 09-28-2011 at 02:22 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Initializing constant object member of a class
    By Canadian0469 in forum C++ Programming
    Replies: 3
    Last Post: 12-03-2008, 08:05 PM
  2. Assigning an object variable to a constant reference
    By Canadian0469 in forum C++ Programming
    Replies: 18
    Last Post: 11-10-2008, 10:48 AM
  3. C++ compared to Java
    By ElastoManiac in forum A Brief History of Cprogramming.com
    Replies: 32
    Last Post: 01-10-2007, 06:46 AM
  4. VB compared to C++
    By C+noob in forum A Brief History of Cprogramming.com
    Replies: 21
    Last Post: 07-14-2005, 01:29 AM
  5. gcc compared to VC6
    By moemen ahmed in forum Linux Programming
    Replies: 1
    Last Post: 07-07-2002, 01:58 AM