Base Copy constructor not called

前端 未结 6 1983
悲&欢浪女
悲&欢浪女 2021-02-10 07:44
class Base
{
      public:
      int i;

      Base()
      {
          cout<<\"Base Constructor\"<

        
相关标签:
6条回答
  • 2021-02-10 08:16

    In your Derived copy constructor, you need to add the following:

    Derived (const Derived &d) : Base(d) { }
    
    0 讨论(0)
  • 2021-02-10 08:16

    C++ doesn't do any kind of "constructor matching". If you do not explicitly call the base class constructor, the default one is called (well, technically, the base class subobject is "value initialized", but for classes with constructors this is the same thing).

    0 讨论(0)
  • 2021-02-10 08:17

    I think you have to explicitly call the base copy constructor:

      Derived (Derived& d) : Base(d)
      {
          cout<<"Derived copy Constructor"<<endl;
          i = d.i; 
      }
    
    0 讨论(0)
  • 2021-02-10 08:19

    If you want to read actual rule you should refer to C++ Standard 12.8/8:

    The implicitly-defined copy constructor for class X performs a memberwise copy of its subobjects. The order of copying is the same as the order of initialization of bases and members in a user-defined construc- tor (see 12.6.2). Each subobject is copied in the manner appropriate to its type:

    • if the subobject is of class type, the copy constructor for the class is used;
    • if the subobject is an array, each element is copied, in the manner appropriate to the element type;
    • if the subobject is of scalar type, the built-in assignment operator is used.

    When you define copy constructor explicitly you should call copy c-tor of base class explicitly.

    0 讨论(0)
  • 2021-02-10 08:32

    Thank you very much. I got it. It means that the call to the base class copy constructor is automagivccally done in the derived's default copy constructor. Whereas in the second case since i am writing the derived's copy constructor i must make an explicit call to the base's copy constructor. Thanks again

    0 讨论(0)
  • 2021-02-10 08:37

    you should read this: it explain how inheritance & special members like constructors are working.

    0 讨论(0)
提交回复
热议问题