Failing constructors

This is a discussion on Failing constructors within the C++ Programming forums, part of the General Programming Boards category; When you have a class the constructor should set all the private variables up but what happens if theres a ...

  1. #1
    Registered User
    Join Date
    May 2004
    Posts
    114

    Failing constructors

    When you have a class the constructor should set all the private variables up but what happens if theres a problem and it can't? I am writing some code to do animations and I will load the details about an animation from a file. All the constructor will take is a filename and it will do the rest, but if the file doesn't exist or theres a problem with it I'm not sure how to handle it as constructors can't return anything back I don't think. Is there a nice way to do this at all? Thanks

  2. #2
    Tropical Coder Darryl's Avatar
    Join Date
    Mar 2005
    Location
    Cayman Islands
    Posts
    503
    well you can use a fail flag and put the class in a "zombie" state the way iostreams does or you can trow an exception.

  3. #3
    Bioport Productions
    Join Date
    Oct 2005
    Posts
    215
    For your situation, I would use the constructor to set all the variables to NULL and make a different function to open the file that can return an error value.
    -"What we wish, we readily believe, and what we ourselves think, we imagine others think also."
    PHP Code:
    sadf 

  4. #4
    Registered User
    Join Date
    Jan 2005
    Posts
    7,338
    I would not make a separate init function. I would use RAII and initialize the object in the constructor and follow Darryl's suggestion of either setting a "bad" flag or throwing an exception. Throwing an exception is better for rare occurrences, so if the file should always be there (because it is put there by your program), then throw an exception if it won't load. If the file is placed there by the user or the user provides the path, these are often wrong, so a fail state might be more appropriate.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. CreateDevice failing
    By MadCow257 in forum Game Programming
    Replies: 6
    Last Post: 03-14-2006, 08:03 PM
  2. constructors, arrays, and new
    By Thantos in forum C++ Programming
    Replies: 6
    Last Post: 05-30-2004, 06:21 PM
  3. initializes all components of failing to false
    By romeoz in forum C++ Programming
    Replies: 21
    Last Post: 08-01-2003, 09:30 PM
  4. Throwing exceptions with constructors
    By nickname_changed in forum C++ Programming
    Replies: 14
    Last Post: 07-08-2003, 09:21 AM
  5. Copy constructors and private constructors
    By Eibro in forum C++ Programming
    Replies: 5
    Last Post: 11-24-2002, 09:16 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21