Object-oriented – proper way to allow access to private list by reference

cencapsulationobject-orientedpointers

I'm trying to provide a by-reference getter to a list of objects in a class. My setup looks something roughly like this:

class c_Container
{
public:
    c_Item* Get(int uid);
private:
    c_Item itemList[10];
}

class c_Item
{
public:
    int uid;
}

c_Item* c_Container::Get(int uid)
{
    for (int i = 0; i < 10; i++)
    {
        if (itemList[i].uid == uid)
        {
            return &itemList[i];
        }
    }

    return NULL;
}

This is a simplistic example showing usage, usually a c_Item object would have other methods that would do other things. We'd want to obtain the c_Item object from itemList by reference or by address so that we can directly modify it.

When compiling, I get a lint error something like "Exposing low access member 'itemList'". If I try to return by reference instead of returning a pointer, I get the same thing. I guess I understand why, but I can't conceive of a better way to obtain an object from a container class like this by reference. I can fix the error by making itemList public, but that seems like unnecessary access.

Outside of creating wrapper methods in c_Container for all of c_Item's methods (which seems redundant), is there a better way to handle a situation like this?

Best Answer

Container classes are an exception to the general rule that you should not provide public access to private members (by returning a pointer or reference in a getter).

However, a lint tool is not smart enough to determine if the container exception should apply to your Get method or not, so it tries to make the safe assumption and generates a warning. Most lint tools can be given additional information through source code annotations. Check the documentation for your tool to see how it can be informed that the warning for this function is a false-positive and should be suppressed.

Related Topic