Search code examples
c++constructormethod-call

Calling base methods from member initializer list


Is it safe to call non-virtual base methods from member initializer list? And virtual?


Solution

  • It is not safe to call any member function (virtual or not virtual) before all base have been initialized. Bellow an example given in the standard ([class.base.init]§16):

    class A {
    public:
      A(int);
    };
    
    class B : public A {
      int j;
    public:
      int f();
      B() : A(f()),     // undefined behavior: calls member function but base A not yet initialized
      j(f()) { }        // well-defined: bases are all initialized
    };
    
    class C {
    public:
      C(int);
    };
    
    class D : public B, C {
      int i;
    public:
      D() : C(f()),     // undefined behavior: calls member function but base C not yet initialized
      i(f()) { }        // well-defined: bases are all initialized
    };
    

    There are more subtle cases.