I'm flumoxed, how do people normally handle

CBaseClass::operator==

and

CDerivedClass::operator==

What I have done is illustrated below, but is it good valid C++? I compare the base class members first (using base class ==) and then the derived class members (the rest of the implementation of the derived class ==).

// This is == in a derived class
bool CFlatMeshGen::operator== (const CFlatMeshGen& Rhs) const 
{
    // First compare the base class members....
    const CMeshGen* pBaseLhs = (CMeshGen*)(this) ;
    const CMeshGen* pBaseRhs = (CMeshGen*)(&Rhs) ;
    if (*pBaseLhs != *pBaseRhs) {
        // We are already not equal....
        return (false) ;
    }
    // If we get here base class members are equal...

    // Compare the derived class members...
    if (m_XSize != Rhs.m_XSize) {
        return (false) ;
    }

    if (m_YSize != Rhs.m_YSize) {
        return (false) ;
    }

    if (m_BaseHeight != Rhs.m_BaseHeight) {
        return (false) ;
    }

    return (true) ;
}

Perfectly functional, if not simple or "elegant". This will do the same, in less code and perhaps more efficiently:

// This is == in a derived class
bool CFlatMeshGen::operator== (const CFlatMeshGen& rhs) const 
{
    // First compare the base class members....
    return ((const CMeshGen&)(*this) == (const CMeshGen&)rhs &&
            m_XSize == rhs.m_XSize &&
            m_YSize == rhs.m_YSize &&
            m_BaseHeight == rhs.m_BaseHeight);
}

One of the advantages of this construct is that the first non-equal element in the test will cause it to return false, so only the minimum element comparisons will be made in non-true cases.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.