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

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
posted @ 2019-12-21 10:02  相印  阅读(231)  评论(0)    收藏  举报