Let's say that I have a class that encapsulates one (or several) members (s) that needs to be initialized in some way, and there is no sensible way to use the class without it (so I don't want to make it optional), Is it better initialization run in its constructor like this:
class MyClass
{
MyClass()
{
if(!obj.initialize()
throw ...;
}
private:
MyObject obj;
}
or you suggest the following design:
class MyClass
{
MyClass()
{
}
bool initialize()
{
return obj.initialize();
}
private:
MyObject obj;
}
The first one looks attractive, because I can guarantee that all the requirements for using my class are met after the constructor starts, and I can report any errors by throwing an exception.
, , , .. , , .. , , ctors , , , . - - , . .
№2, , , , . , , , - (, ). , , # 1.
, ?