Thread: Constructor failure

  1. #1
    Registered User
    Join Date
    Jan 2002
    Location
    Vancouver
    Posts
    2,212

    Constructor failure

    Is there any way you can have a constructor fail so that the class isn't created? i.e.

    Code:
    Socket::Socket(char *addr, int port)
    {
        if (connect(addr, port) == FAIL) {
            fail; 
        }
    }
    Code:
    int main()
    {
        Socket *sock = new Socket("google.com", 80);
        if (sock == NULL) {
           printf("It didn't work\n");
           return 0;
        }
    }

  2. #2
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    You could throw an exception.

    Also in your example code new won't return a NULL if it fails. It'll throw an exception.

    Another option is to just put the object into a failed state.

  3. #3
    Registered User
    Join Date
    Jan 2005
    Posts
    8
    Or make an empty constructor and use a Create() member function which returns a bool.

  4. #4
    Registered User
    Join Date
    Aug 2003
    Posts
    127
    throwing an exception is a easy way

    or you can use safe_bool
    Code:
    class A
    {
       struct dummy{ void non_null(){} };
       typedef void (dummy::*safe_bool)();
       
       bool init();
    public:
       A():is_failed_(false) {  is_failed_ = init();  }
       
       bool failed() const { return is_failed_; }
       
       operator safe_bool() const
       {
           return  (this->failed())? 0 : &dummy::non_null;
       }
    private:
       bool is_failed_;   
    };
    
    int main()
    {
       A a;
       if(a) cout<<"yes"<<endl; else cout<<"no"<<endl;    
    }
    Nana C++ Library is a GUI framework that designed to be C++ style, cross-platform and easy-to-use.

  5. #5
    Registered User
    Join Date
    Aug 2001
    Posts
    244
    oh cause i picked up the topic...

    in case that construction fails how can the memory be cleaned up?
    afaik the memory remains - especially when creation of an member fails it cannot free memory of the "parent" object.
    i think i read something that the member new and delete functions are used to clean such mess up again...
    signature under construction

  6. #6

Popular pages Recent additions subscribe to a feed