Calling virtual functions inside constructors

前端 未结 13 1079

Suppose I have two C++ classes:

class A
{
public:
  A() { fn(); }

  virtual void fn() { _n = 1; }
  int getn() { return _n; }

protected:
  int _n;
};

clas         


        
13条回答
  •  你的背包
    2020-11-21 06:11

    One solution to your problem is using factory methods to create your object.

    • Define a common base class for your class hierarchy containing a virtual method afterConstruction():
    class Object
    {
    public:
      virtual void afterConstruction() {}
      // ...
    };
    
    • Define a factory method:
    template< class C >
    C* factoryNew()
    {
      C* pObject = new C();
      pObject->afterConstruction();
    
      return pObject;
    }
    
    • Use it like this:
    class MyClass : public Object 
    {
    public:
      virtual void afterConstruction()
      {
        // do something.
      }
      // ...
    };
    
    MyClass* pMyObject = factoryNew();
    
    

提交回复
热议问题