Start here

Home
About Klocwork
What's new
Fixed issues
Release notes
Installation

Reference

C/C++ checkers
Java checkers
C# checkers
MISRA C 2004 checkers
MISRA C++ 2008 checkers
MISRA C 2012 checkers
MISRA C 2012 checkers with Amendment 1
Commands
Metrics
Troubleshooting
Reference

Product components

C/C++ Integration build analysis
Java Integration build analysis
Desktop analysis
Refactoring
Klocwork Static Code Analysis
Klocwork Code Review
Structure101
Tuning
Custom checkers

Coding environments

Visual Studio
Eclipse for C/C++
Eclipse for Java
IntelliJ IDEA
Other

Administration

Project configuration
Build configuration
Administration
Analysis performance
Server performance
Security/permissions
Licensing
Klocwork Static Code Analysis Web API
Klocwork Code Review Web API

Community

View help online
Visit RogueWave.com
Klocwork Support
Rogue Wave Videos

Legal

Legal information

MISRA.COPYASSIGN.ABSTRACT

Copy 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.

Rationale

An 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.

Example

class 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.