MISRA.COPYASSIGN.ABSTRACTCopy assignment operator declared public in an abstract class. MISRA-C++ Rule 12-8-2 (required): The copy assignment operator shall be declared protected or private in an abstract class.RationaleAn abstract class represents the interface part of a hierarchy. Invoking the copy constructor from the top of such a hierarchy bypasses the underlying implementation resulting in only the base sub-objects being copied. Exampleclass B1 { public: B1 ( ); virtual void f( ) = 0; B1 & operator= ( B1 const & rhs ); // Non-compliant int32_t getKind ( ) const { return kind; } private: int32_t kind; }; class D1 : public B1 { public: virtual void f ( ) { } D1 & operator= ( D1 const & rhs ); private: int32_t member; }; void f1( B1 & b1, B1 & b2 ) { b1 = b2; } As the assignment operator is public, the function 'f1' can call the operator and so copies the base sub-objects of b1 and b2. As the type of 'b1' and 'b2' is an abstract type, 'b1' and 'b2' must be sub-objects, and so the information contained in the derived objects for both will not be copied. Making the abstract copy assignment operator protected allows access from the derived classes but not from outside the hierarchy. class B2 { public: B2 ( ); virtual void f ( ) = 0; int32_t getKind ( ) const { return kind; } protected: B2 & operator= ( B2 const & rhs ); // Compliant private: int32_t kind; }; class D2 : public B2 { public: virtual void f ( ) { } D2 & operator= ( D2 const & rhs ); }; void f2 ( B2 & b1, B2 & b2 ) { b1 = b2; // Compiler error will be reported } Making the copy assignment operator private is a common idiom used to restrict copying objects of the class type. |