0

I have a problem understanding when the default constructor of a class member is called. My class MyClass has a member of class Reader. In the constructor of MyClass I need to call the constructor of Reader and catch an Exception in case it fails. Because in the rest of MyClass's functions, I need to know if it was instantiated successfully and if I can use it. I know that I can call the default constructor in the initializer list. But when do I call it in the constructor? What's the common approach here?

class MyClass {
public:
    MyClass() {
        hasReader = true;
        try{
            //Call Reader constructor here
        }
        catch(Exception)
        {
            hasReader = false;
        }
    }

protected:
    Reader mReader;
    bool hasReader;
};

class Reader {
public:
    Reader()
    {
        bConnected = true;
        if (something fails)
        {
            bConnected = false;   
            throw new Exception();
        }
    }

protected:
    bool bConnected;
};
iksemyonov
  • 4,106
  • 1
  • 22
  • 42
tzippy
  • 6,458
  • 30
  • 82
  • 151
  • I am not sure about this, but as far as I know it won't be possible without placing data member within ctor's initializer list, because in your case Reader's ctor will be invoked before code in your ctor executes. So you would have to surround MyClass creation with try-catch block. – Piotr Smaroń Feb 08 '16 at 08:44
  • You might want to look up *member initializer list* before that. You don't work with classes without knowing about it. – LogicStuff Feb 08 '16 at 08:44
  • @LogicStuff I do know about it but I thought that I can't use it here because there's no way of surrounding an initializer list with a try-catch. Appearently I was wrong. – tzippy Feb 08 '16 at 08:46
  • The exception will still escape to the caller. Which is probably not what you want since you set a flag when Reader fails to initialize. You probably want to hold a smart pointer to Reader and initialize it in your constructor's body. That way you can catch any exceptions thrown in the constructor and set your flag. – Mohamad Elghawi Feb 08 '16 at 08:48
  • Thanks @MohamadElghawi !! – tzippy Feb 08 '16 at 08:50

0 Answers0