假设我有两个c++类:

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

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

protected:
  int _n;
};

class B : public A
{
public:
  B() : A() {}

  virtual void fn() { _n = 2; }
};

如果我写下面的代码:

int main()
{
  B b;
  int n = b.getn();
}

有人可能认为n被设为2。

结果是n被设为1。为什么?


当前回答

我刚刚在一个程序中出现了这个错误。 我有这样的想法:如果方法在构造函数中被标记为纯虚函数会发生什么?

class Base {
public:
    virtual int getInt() = 0;
    
    Base(){
        printf("int=%d\n", getInt());
    }
};

class Derived : public Base {
    public:
        virtual int getInt() override {return 1;}
};

和…有趣的事情!你首先得到编译器的警告:

warning: pure virtual ‘virtual int Base::getInt() const’ called from constructor

和一个来自ld的错误!

/usr/bin/ld: /tmp/ccsaJnuH.o: in function `Base::Base()':
main.cpp:(.text._ZN4BaseC2Ev[_ZN4BaseC5Ev]+0x26): undefined reference to `Base::getInt()'
collect2: error: ld returned 1 exit status

这是完全不合逻辑的,你只得到一个警告从编译器!

其他回答

在对象的构造函数调用期间,虚函数指针表没有完全构建。这样做通常不会给你带来你期望的行为。在这种情况下调用虚函数可能有效,但不能保证,应该避免使用,以便便于移植并遵循c++标准。

在大多数OO语言中,从构造函数调用多态函数是导致灾难的原因。遇到这种情况时,不同的语言会有不同的表现。

基本问题是,在所有语言中,基类型必须在派生类型之前构造。现在,问题是从构造函数调用多态方法意味着什么。你希望它表现得怎样?有两种方法:在基本层调用方法(c++风格)或在层次结构底部的未构造对象上调用多态方法(Java方式)。

In C++ the Base class will build its version of the virtual method table prior to entering its own construction. At this point a call to the virtual method will end up calling the Base version of the method or producing a pure virtual method called in case it has no implementation at that level of the hierarchy. After the Base has been fully constructed, the compiler will start building the Derived class, and it will override the method pointers to point to the implementations in the next level of the hierarchy.

class Base {
public:
   Base() { f(); }
   virtual void f() { std::cout << "Base" << std::endl; } 
};
class Derived : public Base
{
public:
   Derived() : Base() {}
   virtual void f() { std::cout << "Derived" << std::endl; }
};
int main() {
   Derived d;
}
// outputs: "Base" as the vtable still points to Base::f() when Base::Base() is run

In Java, the compiler will build the virtual table equivalent at the very first step of construction, prior to entering the Base constructor or Derived constructor. The implications are different (and to my likings more dangerous). If the base class constructor calls a method that is overriden in the derived class the call will actually be handled at the derived level calling a method on an unconstructed object, yielding unexpected results. All attributes of the derived class that are initialized inside the constructor block are yet uninitialized, including 'final' attributes. Elements that have a default value defined at the class level will have that value.

public class Base {
   public Base() { polymorphic(); }
   public void polymorphic() { 
      System.out.println( "Base" );
   }
}
public class Derived extends Base
{
   final int x;
   public Derived( int value ) {
      x = value;
      polymorphic();
   }
   public void polymorphic() {
      System.out.println( "Derived: " + x ); 
   }
   public static void main( String args[] ) {
      Derived d = new Derived( 5 );
   }
}
// outputs: Derived 0
//          Derived 5
// ... so much for final attributes never changing :P

如您所见,调用多态(c++术语为虚拟)方法是一个常见的错误来源。在c++中,至少你可以保证它永远不会对一个尚未构造的对象调用方法……

你知道Windows资源管理器的崩溃错误吗?“纯虚函数调用…” 同样的问题…

class AbstractClass 
{
public:
    AbstractClass( ){
        //if you call pureVitualFunction I will crash...
    }
    virtual void pureVitualFunction() = 0;
};

由于pureVitualFunction()函数没有实现,并且在构造函数中调用该函数,因此程序将崩溃。

为了回答当你运行这段代码时会发生什么/为什么,我通过编译它 g++ -ggdb main。Cc,并逐步使用gdb。

main.cc:

class A { 
  public:
    A() {
      fn();
    }
    virtual void fn() { _n=1; }
    int getn() { return _n; }

  protected:
    int _n;
};


class B: public A {
  public:
    B() {
      // fn();
    }
    void fn() override {
      _n = 2;
    }
};


int main() {
  B b;
}

在main处设置断点,然后进入B(),打印this ptr,进入a()(基构造函数):

(gdb) step
B::B (this=0x7fffffffde80) at main2.cc:16
16    B() {
(gdb) p this
$27 = (B * const) 0x7fffffffde80
(gdb) p *this
$28 = {<A> = {_vptr.A = 0x7fffffffdf80, _n = 0}, <No data fields>}
(gdb) s
A::A (this=0x7fffffffde80) at main2.cc:3
3     A() {
(gdb) p this
$29 = (A * const) 0x7fffffffde80

显示它最初指向派生的B对象B,该对象B被构造在0x7fffffffde80的堆栈上。下一步是进入以A()为基数的ctor,这变成了A * const到相同的地址,这是有意义的,因为以A为基数的对象正好在B对象的开头。但它仍然没有被构建:

(gdb) p *this
$30 = {_vptr.A = 0x7fffffffdf80, _n = 0}

还有一步:

(gdb) s
4       fn();
(gdb) p *this
$31 = {_vptr.A = 0x402038 <vtable for A+16>, _n = 0}

_n已经初始化,它的虚函数表指针包含虚void A::fn()的地址:

(gdb) p fn
$32 = {void (A * const)} 0x40114a <A::fn()>
(gdb) x/1a 0x402038
0x402038 <_ZTV1A+16>:   0x40114a <_ZN1A2fnEv>

因此,下一步通过this->fn()执行A::fn()是完全有意义的,前提是活动this和_vptr.A。再一步,我们回到B() ctor:

(gdb) s
B::B (this=0x7fffffffde80) at main2.cc:18
18    }
(gdb) p this
$34 = (B * const) 0x7fffffffde80
(gdb) p *this
$35 = {<A> = {_vptr.A = 0x402020 <vtable for B+16>, _n = 1}, <No data     fields>}

碱基A已经构造好了。注意,存储在虚函数表指针中的地址已经更改为派生类B的虚表,因此调用fn()将通过this->fn()选择派生类重写B::fn(),给定活动this和_vptr。A(在B()中调用B::fn()来查看这个。)再次检查存储在_vptr中的1个地址。A显示它现在指向派生类重写:

(gdb) p fn
$36 = {void (B * const)} 0x401188 <B::fn()>
(gdb) x/1a 0x402020
0x402020 <_ZTV1B+16>:   0x401188 <_ZN1B2fnEv>

By looking at this example, and by looking at one with a 3 level inheritance, it appears that as the compiler descends to construct the base sub-objects, the type of this* and the corresponding address in _vptr.A change to reflect the current sub-object being constructed, - so it gets left pointing to the most derived type's. So we would expect virtual functions called from within ctors to choose the function for that level, i.e., same result as if they were non-virtual.. Likewise for dtors but in reverse. And this becomes a ptr to member while members are being constructed so they also properly call any virtual functions that are defined for them.

解决这个问题的一个方法是使用工厂方法来创建对象。

为你的类层次结构定义一个公共基类,其中包含一个虚拟方法afterConstruction():

class Object
{
public:
  virtual void afterConstruction() {}
  // ...
};

定义一个工厂方法:

template< class C >
C* factoryNew()
{
  C* pObject = new C();
  pObject->afterConstruction();

  return pObject;
}

像这样使用它:

class MyClass : public Object 
{
public:
  virtual void afterConstruction()
  {
    // do something.
  }
  // ...
};

MyClass* pMyObject = factoryNew();