Hi, folks,
I am read the book <Efficient C++>. It says:
When you implement your own Copy Constructor for a derived class, you need to explicitly call its Base Copy Constructor, otherwise the member in Base won't be copied. I really am confused why you can call a copy constructor directly .
Look at the code below:
The result is:Code:class A{ public: int x; A():x(0){} A(const A& rhs){ //x=rhs.x; //intentionally comment this out cout<<"A::A(const A& rhs)"<<endl; } void check(){cout<<x<<endl;} }; class B : public A{ public: int y; B():y(0){} B(const B& rhs):A(rhs){ y = rhs.y; cout<<"B::B(const B& rhs)"<<endl; }; }; class C : public A{ public: int y; C():y(0){} C(const C& rhs){ y = rhs.y; cout<<"C::C(const C& rhs)"<<endl; }; }; int main(){ B obj1; obj1.x=1; B obj2(obj1); obj2.check(); C obj3; obj3.x=1; C obj4(obj3); ojb4.check(); return 0; }
My questions are:A::A(const A& rhs)
B::B(const B& rhs)
1073836148
C::C(const C& rhs)
0
1) When C's copy constructor is called, does it call C::A() to initialize x ?
2). Can we call a Copy Constructor directly like this:
?Code:B(const B& rhs):A(rhs)
Why
gets a complier error?Code:B(const B& rhs){ A(rhs); }
Thanks!



LinkBack URL
About LinkBacks




CornedBee