C++ Class Question

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sake
    New Member
    • Jan 2007
    • 46

    C++ Class Question

    Hi,

    I recently came about an article on cplusplus.com regarding exception handling and, specifically, a code excerpt:
    Code:
    // standard exceptions
    #include <iostream>
    #include <exception>
    using namespace std;
    
    class myexception: public exception
    {
      virtual const char* what() const throw()
      {
        return "My exception happened";
      }
    } myex;
    
    int main () {
      try
      {
        throw myex;
      }
      catch (exception& e)
      {
        cout << e.what() << endl;
      }
      return 0;
    }
    The part that confuses me is after the class myexception is declared.
    Code:
    class myexception: public exception
    {
      virtual const char* what() const throw()
      {
        return "My exception happened";
      }
    } myex;
    The last word of this snippet outside the braces: myex;. What does this mystery word mean and do? After looking at the code, I figured it may have been a shortcut to referring to the class, but it seems silly to have do that when you could just make the class's name "myex". Anyone care to shed some light on this for me?

    Thanks,
    Austen
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    It is declaring a variable named myex of type myexception. The code is equivalent to

    Code:
    class myexception: public exception
    {
      virtual const char* what() const throw()
      {
        return "My exception happened";
      }
    };
    
    myexception myex;

    Comment

    • sake
      New Member
      • Jan 2007
      • 46

      #3
      Ah, I see.
      Thank you very much.
      -Austen

      Comment

      Working...