C ++中的虚拟构造函数

仅当我们具有指向派生类对象的基类指针时,虚拟机制才起作用。

在C ++中,构造函数不能是虚拟的,因为执行类的构造函数时,内存中没有虚拟表,这意味着尚未定义虚拟指针。因此,构造函数应始终是非虚拟的。

但是虚拟析构函数是可能的。

范例程式码

#include<iostream>
using namespace std;
class b {
   public:
      b() {
         cout<<"Constructing base \n";
      }
      virtual ~b() {
         cout<<"Destructing base \n";
      }
};
class d: public b {
   public:
      d() {
         cout<<"Constructing derived \n";
      }
      ~d() {
         cout<<"Destructing derived \n";
      }
};
int main(void) {
   d *derived = new d();
   b *bptr = derived;
   delete bptr;
   return 0;
}

输出结果

Constructing base
Constructing derived
Destructing derived
Destructing base