Calling virtual functions inside constructors

前端 未结 13 1092

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

    The C++ FAQ Lite Covers this pretty well:

    Essentially, during the call to the base classes constructor, the object is not yet of the derived type and thus the base type's implementation of the virtual function is called and not the derived type's.

提交回复
热议问题