error C2248 when using a CObject-derived class as CList's type parameter

1.4k Views Asked by At

Let's suppose that I have the following classes declared in my MFC project:

class CProfession : public CObject
{
public:
    CProfession();
    virtual ~CProfession();

    int ID;
    CString name;
};

class CPerson : public CObject
{
public:
    CPerson();
    virtual ~CPerson();

    int ID;
    CString name;
    int age;
    CString email;
    CList<CProfession, CProfession&> profession;
};

Due to the CList declaration (as it was shown right above), I get the following error: error C2248: 'CObject::operator =' : cannot access private member declared in class 'CObject'.

I've already tried to implement many kinds of overloadings and copy constructors, but I didn't had any success. I realize that there are other possibilities for solving this error, such as using pointers, but I really looking for a solution that fits exactly in the code that I provided. Does anyone knows how to solve this?

1

There are 1 best solutions below

7
On

Since operator=(const CObject&) is declared private in the base class you have to provide a public assignment operator in your derived class:

CProfession& operator=( const CProfession& other ) {
    this->ID = other.ID;
    this->name = other.name;
    return *this;
}

Depending on the semantics you want to implement you may have to adjust the implementation to your requirements.

Also keep in mind the Rule of three, a rule of thumb claiming that if a class defines one of the following it should probably define all three:

  • destructor
  • copy constructor
  • copy assignment oprator

All of the above are implicitly implemented by the compiler unless they are declared by the programmer. The rationale of the Rule of three is that if one of the compiler-generated member functions does not fit the needs of a class and has to be defined by the programmer, then the others will probably not fit either.