C++ - Calling virtual function from constructor

<!-- X-Subject-Header-End--> <!-- X-Head-of-Message-->
  • From : Rob Newberry <robnewberry at grouplogic dot com>
  • To : Eddy Ilg <eddy at fericom dot net>
  • Cc : gcc-help at gcc dot gnu dot org
  • Date : Thu, 22 Nov 2001 12:58:25 -0500 (EST)
  • Subject : Re: C++ - Calling virtual function from constructor
<!-- X-Head-of-Message-End--><!-- X-Head-Body-Sep-Begin-->
<!-- X-Head-Body-Sep-End--><!-- X-Body-of-Message-->
The reason you don't call virtual methods inside a constructor is because
you don't know what kind of object you are -- while you're in the process
of being constructed, you're still in a _somewhat_ indeterminate state.
Only after you are constructed are you a real object.

Here's an example:

	class	a
	{
		public:
			a();

			virtual void v_meth();
	};

	class	b : public a
	{
		public:
			b();

			virtual void v_meth();
	};


	a::a()
	{
		// this will _always_ call a::v_meth, because
		// at this point, that's what we are -- even
		// if we're in the process of constructing a 
		// subclass of class a
		v_meth();
	}

	void a::v_meth()
	{
		printf("a::v_meth\n");
	}

	b::b()
	{
		// likewise, this will always call b::v_meth,
		// because at this point, that's what we are
		v_meth();
	}

	void b::v_meth()
	{
		printf("b::v_meth\n");
	}

	main()
	{
		printf("constructing an a:\n");
		a	an_a;

		printf("constructing a b:\n");
		b	a_b;
	}
	
The output of this, with gcc, is:

	constructing an a:
	a::v_meth
	constructing a b:
	a::v_meth
	b::v_meth

As you can see, when you are constructing the 'b' object a_b, the
constructor for 'a' and 'b' get called in succession.  But the constructor
for 'a' calls 'v_meth', it ONLY calls the 'a' method, because at that
point, that's all the object it is.  This might not be the behavior you
want to have, since you're constructing a 'b' object.  That's why the
compiler complains about you calling a virtual method in a constructor.

Rob

---------------------------------------------------------------------
Rob Newberry
Director of Fajita Technology
Group Logic, Inc.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值