Why does the implicit copy constructor calls the base class copy constructor and the defined copy constructor doesn't?

前端 未结 3 1989
醉话见心
醉话见心 2020-12-12 17:25

Consider a class hierarchy where A is the base class and B derives from A.

If the copy constructor is not defined in B

相关标签:
3条回答
  • 2020-12-12 18:00

    The simple (possibly trite) answer is because you didn't tell it to. Since you are writing the derived copy constructor, you completely control how it behaves. Failure to specify a call to the base and the compiler generates code to initialize the base class by calling the base classes default constructor.

    0 讨论(0)
  • 2020-12-12 18:01

    That's just the way the implicit copy constructor is defined (it wouldn't make sense calling the default). As soon as you define any constructor (copy or otherwise) its normal automatic behavior is to call the default parent constructor, so it would be inconsistent to change that for one specific user-defined constructor.

    0 讨论(0)
  • 2020-12-12 18:06

    All base child constructors call the parent default constructor. This is how the standard is defined. As you pointed out if you wanted the derive class B to call A's copy constructor you have to explicitly ask for it

    #include <iostream>
    
    class A {
    int a;
    public:
    A() {
        std::cout << "A::Default constructor" << std::endl;
    }
    
    A(const A& rhs) {
        std::cout << "A::Copy constructor" << std::endl;
    }
    };
    
    class B : public A {
    int b;
    public:
    B() {
        std::cout << "B::Default constructor" << std::endl;
    }
    B(const B& rhs):A(rhs) {
        std::cout << "B::Copy constructor" << std::endl;
    }
    };
    
    int main(int argc, const char *argv[])
    {
    std::cout << "Creating B" << std::endl;
    B b1;
    std::cout << "Creating B by copy" << std::endl;
    B b2(b1);
    return 0;
    }
    

    This is so because the compiler can't know for each different constructor which constuctor of the parent should be called and hence we have the default constructors For all others you have to explicitly state them.

    Output:

    Creating B
    A::Default constructor
    B::Default constructor
    Creating B by copy
    A::Copy constructor
    B::Copy constructor
    
    0 讨论(0)
提交回复
热议问题