none
is it practical to call winAPI functions inside a class constructor?

    Question

  • in all tutorials I've read it's always about variable initialization when it comes to constructors

    and those variables are always initialized with constants

    I'm wondering if it's practical to make calls to winAPI functions in the constructor and assign their return values to the class data members

    thanks

    • Edited by ColdBackup Monday, July 16, 2012 3:12 AM
    Monday, July 16, 2012 3:11 AM

Answers

  • ColdBackup wrote:

    I'm wondering if it's practical to make calls to winAPI functions in  the constructor and assign their return values to the class
    data members

    One problem is that a constructor doesn't have an easy way to signal  failure. If any of those WinAPI calls fail, either the constructor would  have to throw an exception (and the user of your class will have to be  prepared for that), or you would end up with an object in some  partially-constructed state.

    For these reason, many experts recommend against performing significant  work in a constructor, especially work that could fail.


    Igor Tandetnik

    • Marked as answer by ColdBackup Monday, July 16, 2012 3:28 AM
    Monday, July 16, 2012 3:27 AM

All replies

  • ColdBackup wrote:

    I'm wondering if it's practical to make calls to winAPI functions in  the constructor and assign their return values to the class
    data members

    One problem is that a constructor doesn't have an easy way to signal  failure. If any of those WinAPI calls fail, either the constructor would  have to throw an exception (and the user of your class will have to be  prepared for that), or you would end up with an object in some  partially-constructed state.

    For these reason, many experts recommend against performing significant  work in a constructor, especially work that could fail.


    Igor Tandetnik

    • Marked as answer by ColdBackup Monday, July 16, 2012 3:28 AM
    Monday, July 16, 2012 3:27 AM
  • for me, the determination is this:

    If I create the object with the expectation there is no point in the object's existence if the API call should fail, I happily put it in the constructor. If the API call fails, I will do whatever cleanup is necessary, and simply throw an exception.

    If the success of the API call has no bearing on the lifetime of the object, I keep it out of the constructor.

    Monday, July 16, 2012 12:56 PM