Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ overloading assignment operator

Tags:

c++

mfc

I have a class called Location and I needed to add a CArray to its member variables. This change caused the need to overload the assignment operator.

Is there a way to copy all of the variables in this class type that were being copied before I made the change and just add the additional code to copy the CArray without copying every single member variable individually?

Location& Location::operator=(const Location &rhs) 
{
    // Only do assignment if RHS is a different object from this.
    if (this != &rhs) 
    {
        //Copy CArray
        m_LocationsToSkip.Copy(rhs.m_LocationsToSkip);

        //Copy rest of member variables
        //I'd prefer not to do the following
        var1 = rhs.var1;
        var2 = rhs.var2;
        //etc
    }

    return *this;
}
like image 365
Cole W Avatar asked Jan 14 '12 23:01

Cole W


Video Answer


1 Answers

Yes, sort of. Use a type that overloads operator= itself, so you don't have to do it in the containing class instead. Even when writing MFC code, I still mostly use std::vector, std::string, etc., instead of the MFC collection and string classes. Sometimes you're pretty much stuck using CString, but I can't recall the last time I used CArray instead of std::vector.

like image 128
Jerry Coffin Avatar answered Sep 30 '22 00:09

Jerry Coffin