Should I use virtual 'Initialize()' functions to initialize an object of my class?

后端 未结 13 1544
孤独总比滥情好
孤独总比滥情好 2020-12-17 14:33

I\'m currently having a discussion with my teacher about class design and we came to the point of Initialize() functions, which he heavily promotes. Example:

13条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-17 14:54

    If you use it, then you should make the constructor private and use factory methods instead that call the initialize() method for you. For example:

    class MyClass
    {
    public:
        static std::unique_ptr Create()
        {
            std::unique_ptr result(new MyClass);
            result->initialize();
            return result;
        }
    
    private:
        MyClass();
    
        void initialize();
    };
    

    That said, initializer methods are not very elegant, but they can be useful for the exact reasons your teacher said. I would not consider them 'wrong' per se. If your design is good then you probably will never need them. However, real-life code sometimes forces you to make compromises.

提交回复
热议问题