c++ - Implementation supplied copy constructor and assignment operator -
i have small confusion regarding situations implementation (compiler) not supply copy constructor , copy assignment operator.
- when declare copy ctor and/or copy assignment operator in our class.
- some says when derive class has private copy ctor and/or copy assignment operator.
i little confused second situation, second situation precisely.
a) implementation not declare them you, compile time error.
or
b) implementation declare , define them, when compiler defined implementation tries find base class' method, compile time error.
i had interview yesterday, said (b) happening interviewer disagrees, says (a).
i tried compile following code in both microsoft c/c++ 14.00 , gcc 4.4.5
struct { private: a& operator = ( const a& ); }; struct b : { }; int main() { b b1; b b2; b1 = b2; return 0; } microsoft compiler output
ctor01.cpp(9) : error c2248: 'a::operator =' : cannot access private member declared in class 'a' ctor01.cpp(4) : see declaration of 'a::operator =' ctor01.cpp(2) : see declaration of 'a' diagnostic occurred in compiler generated function 'b &b::operator =(const b &)' gcc compiler output
ctor01.cpp: in member function ‘b& b::operator=(const b&)’: ctor01.cpp:4: error: ‘a& a::operator=(const a&)’ private ctor01.cpp:8: error: within context ctor01.cpp: in function ‘int main()’: ctor01.cpp:15: note: synthesized method ‘b& b::operator=(const b&)’ first required here so think, implementation declare , define it, when compiler defined implementation tries find base class method, compile time error. correct me if wrong.
regarding copy constructor, standard says (12.8/7) :
a program illformed if class copy constructor implicitly defined has:
- a nonstatic data member of class type (or array thereof) inaccessible or ambiguous copy constructor, or
- a base class inaccessible or ambiguous copy constructor.
regarding copy assignment operator (12.8/12) :
a program illformed if class copy assignment operator implicitly defined has:
- a nonstatic data member of const type, or
- a nonstatic data member of reference type, or
- a nonstatic data member of class type (or array thereof) inaccessible copy assignment operator, or
- a base class inaccessible copy assignment operator.
how compiler reports error, or how falls it, pretty irrelevant point of view.
however, believe answer (b) more correct : base class copy assignment declared, , it's inaccessible. derived class has implicitly declared copy assignment compiler try define if used, making program ill-formed.
Comments
Post a Comment