首页 > 其他 > 详细

自定义的拷贝构造函数不会调用基类的

时间:2019-12-21 10:58:24      阅读:105      评论:0      收藏:0      [点我收藏+]

You can:

Derived(const Derived& d) : Base(d) {
    cout << "Derived::Derived(const B&)" << endl;
}

This calls the Base copy constructor on the Base sub-object of d.

The answer for ‘why‘ I don‘t know. But usually there‘s no answer. The committee just had to choose one option or the other. This seems more consistent with the rest of the language, where e.g. Derived(int x) won‘t automatically call Base(x).

Ah, I forgot about this feature, but why isn‘t this the default? – Seth Carnegie Jan 7 ‘12 at 20:58

 

  • 3
 
 
    • @Seth: The default copy-constructor DOES copy all subobjects, including base class(es), by calling their copy constructors. – Ben Voigt Jan 29 ‘12 at 23:10
    • 1
       
    • @BenVoigt sorry, I meant why isn‘t it the default behaviour of self-written copy ctors, not why it isn‘t what the default copy ctor does. – Seth Carnegie Jan 29 ‘12 at 23:12
    • @Seth: Ahh, that‘s just for consistency. You use the ctor-initializer-list to specify how to construct subobjects in all other cases, why not the copy constructor also? And how would you specify you don‘t want the base (or any member) copy-constructed? – Ben Voigt Jan 29 ‘12 at 23:32
    •  
    • @BenVoigt is the copy constructor considered to be constructing a subobject? And I don‘t know how you‘d specify you don‘t want the base copy-constructed, but you can‘t specify that you don‘t want the base just plain constructed either – Seth Carnegie Jan 29 ‘12 at 23:38
 
 
@Sean: Each base subobject is a subobject just like members, except base subobjects are constructed before member subobjects. If you don‘t list a subobject in the ctor-initializer-list, you get default initialization (different from value initialization, which is what you get by listing the subobject with a pair of empty parentheses). – Ben Voigt Jan 29 ‘12 at 23:41

自定义的拷贝构造函数不会调用基类的

原文:https://www.cnblogs.com/xiang-yin/p/12076088.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!