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;
};