联系
Knight's Tale » 技术

Never call virtual functions during construction

2010-06-02 16:21

I read <Effective C++> at one time, and I know there is a criterion which is "Never call virtual functions during construction and destruction". But as we all know, genuine knowledge comes from practice. We will never have in-depth understanding of knowledge unless we touch them by ourselves.

Today I want to write a class with Factory patterns in C++.

class DemoModelClass
{
public :
    // common functions
    DemoModelClass() 
{ CreateDemoModelResourceFactory(); // 1st problem! CreateOtherData(); }

private: virtual void CreateDemoModelResourceFactory()=0{}; // 2nd problem! void CreateOtherData(){.....}; }

The above codes have several problems.

First, the construction method will call its own virtual method and not the derived class method.

Second, you should never have implemented codes for  Factory method in base class in Factory Patterns.

So , the right version of the codes must be :

class DemoModelClass
{
public :
    // common functions
    DemoModelClass(){}
    void CreateDemoModelData()
    {
        CreateDemoModelResourceFactory();
        CreateOtherData();
    }   

private: virtual void CreateDemoModelResourceFactory()=0; void CreateOtherData(.....); }

Good Luck for you!