Qt-Autosar-A10.3.5ΒΆ

A user-defined assignment operator shall not be virtual

Required inputs: IR

Assignment operators should not be declared virtual, since this can lead to potentially unexpected behavior. For example, given a virtual assignment operator in a base class B, with overrides in derived classes D1 and D2, it is possible to call the assignment operator of D1 with a parameter of type D2. This is because the parameter list of an override must match that of the base class declaration. In the case of an assignment operator, this will take a parameter of the base class type or reference to it.
Bad code (virtual assignment operator):
class Base {
public:
    virtual Base& operator=(const Base& other) {  // ERROR: virtual
        return *this;
    }
};

class Derived1 : public Base {
public:
    Derived1& operator=(const Base& other) override;
};

class Derived2 : public Base {
public:
    Derived2& operator=(const Base& other) override;
};

void Use() {
    Derived1 d1;
    Derived2 d2;
    d1 = d2; // Calls Derived1::operator=(const Base&)
}
Good code (non-virtual assignment operator):
class Base {
public:
    Base& operator=(const Base& other) {  // OK: non-virtual
        // Base assignment logic
        return *this;
    }
};

class Derived : public Base {
public:
    Derived& operator=(const Derived& other) {  // OK: different signature
        Base::operator=(other);
        // Derived-specific assignment logic
        return *this;
    }
};

Possible Messages

Key

Text

Severity

Disabled

assignment_virtual

A user-defined assignment operator shall not be virtual.

None

False

Options