AlexSavAlexandrov
AlexSavAlexandrov

Reputation: 873

Adding data to CArray gives error "cannot access private member declared in class 'CObject'"

I have a structure called PERSONS and then I have defined a type CTypedPtrArray<CPtrArray, PERSONS*> PersonsTable;

struct Persons { ... };
typedef CTypedPtrArray<CPtrArray, PERSONS*> PersonsTable;

Later in the code I try to make a PersonTable CArray:

void CArrayTesting()
{
    CArray<PersonsTable, PersonsTable> oCArr;
    oCArr.SetSize(3);
    PersonsTable perTableA;
    PersonsTable perTableB;
    PersonsTable perTableC;
    for (int i = 0; i < 10; i++)
    {
        if (i < 3)      addPerson(perTableA, i);
        else if (i < 8) addPerson(perTableB, i);
        else            addPerson(perTableC, i);
    }
    oCArr.Add(perTableA);
    oCArr.Add(perTableB);
    oCArr.Add(perTableC);
    for (int nArrCnt = 0; nArrCnt < oCArr.GetSize(); nArrCnt++)
        for (int i = 0; i < oCArr.ElementAt(nArrCnt).GetSize(); i++)
        {
            cout<<"Table "<< nArrCnt << " - " << oCArr.ElementAt(nArrCnt)[i]->nID << endl;
            delete oCArr.ElementAt(nArrCnt)[i];
        }
}

The addPerson() function adds data to PersonTable.

However, this causes an error during the compilation: cannot access private member declared in class 'CObject . The error appears to be related to oCArr.Add(), because it gets 'fixed' when I delete the respected rows.

Why does the error appear? How can I fix it? And how does CArray work?

Upvotes: 1

Views: 225

Answers (2)

Mercury Dime
Mercury Dime

Reputation: 1601

1201 is correct, and it's a massive headache. If you're forced to use the MFC collections, you could derive from them and create custom copy constructors/assignment operators. (and move + initializer_list) The array collections have a Copy function you can use to make life simple.

class CPtrArrayEx : public CPtrArray
{
public:
    CPtrArrayEx() = default;
    CPtrArrayEx(CPtrArrayEx const& rhs)
    {
        Copy(rhs);
    }

    CPtrArrayEx& operator=(CPtrArrayEx const& rhs)
    {
        if (this != &rhs)
            Copy(rhs);
        return *this;
    }
};

Upvotes: 1

1201ProgramAlarm
1201ProgramAlarm

Reputation: 32727

The error boils down to class CPtrArray not defining a copy constructor, which your code uses when adding to oCArr. The compiler generated default copy constructor will try to call the copy constructor for CObject, which is declared private.

You should probably add the elements into oCArr directly, rather than adding them to local variables then making copies.

Upvotes: 2

Related Questions