R6025调用纯虚函数错误

本文探讨了在C++中构造函数内调用虚函数导致的问题,特别是在对象尚未完全构建完成时调用虚函数可能导致错误。文章通过具体代码示例解释了为何此时会调用基类的虚函数而非派生类的实现,并总结了避免此类问题的最佳实践。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

   class A;

   void fcn( A* );

   class A
   {
   public:
	   virtual void f()=0;
	   A() { fcn(this); }
   };

   class B : A
   {
       void f() { }
   };

   void fcn( A* p )
   {
       p->f();//here, call the version of class A.
   }



int main(int argc, char **argv)
{
	/*construct object A first, in constructor of class A, it call virtual function f(); theoretically it should call 
        the version of class B, because it is object B. But at this time, object b has not been fully constructed yet. 
        That means the virtual function table has not been built up yet. so it actually calls the version of class A, 
        which cause the error of R6025*/
	B b;
	return 0;
}


所以结论是在构造函数和析构函数中不要调用虚函数,实际项目中case会比较复杂,往往没有这么容易看出来

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值