CPU-return-ref-to-class-data (C++ only)
Synopsis
Member functions return non-const handles to members.
Enabled by default
Yes
Severity/Certainty
Medium/High

Full description
Member functions return non-const handles to members. Implement class interfaces with member functions to retain more control over how the object state can be modified and to make it easier to maintain a class without affecting clients. Returning a handle to class-data allows clients to modify the state of the object without using any interfaces. This check is identical to MISRAC++2008-9-3-2.
Coding standards
- CERT OOP35-CPP
Do not return references to private data
- MISRA C++ 2008 9-3-2
(Required) Member functions shall not return non-const handles to class-data.
Code examples
The following code example fails the check and will give a warning:
class C{
int x;
public:
int& foo();
int* bar();
};
int& C::foo() {
return x; //returns a non-const reference to x
}
int* C::bar() {
return &x; //returns a non-const pointer to x
}
The following code example passes the check and will not give a warning about this issue:
class C{
int x;
public:
const int& foo();
const int* bar();
};
const int& C::foo() {
return x; //OK - returns a const reference
}
const int* C::bar() {
return &x; //OK - returns a const pointer
}