What design to choose to initialize complex objects?

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.

, ?

+4
2

" , , , ..."

.

, - undefined .

, , .

.

, std::fstream. fstream - :

std::fstream fs; // initialized but not configured

undefined .

, - , :

fs.open("myfile.txt", std::ios::in); // configured

, .

, , :

std::fstream fs("myfile.txt", std::ios::in); // initialized & configured
+4

MyObject::initialize MyObject ( throw). MyClass .

+3

Source: https://habr.com/ru/post/1628294/


All Articles