Vinícius
Vinícius

Reputation: 15746

Class reference grants access to private member

I was writting a class for 'turning' modes on-off easily, then I got a bit confused. On the overloaded operator= to copy from another class, access to the private T member m_Modeis granted, why does this happen? Is it sandard, or perhaps a compiler bug?

template<class T>
class CFixedMode
{
private:
    T m_Mode;
public:
    CFixedMode()
    {
        m_Mode = static_cast<T>(0);
    }
    ~CFixedMode(){}
    void            SetMode( T mode );
    void            SetNotMode( T mode );
    BOOL            IsMode( T mode );
    CFixedMode<T>&              operator=( const CFixedMode< T >& rFixedMode );
};

template<class T>void CFixedMode<T>::SetMode( T mode )
{
    m_Mode |= mode;
}
template<class T>void CFixedMode<T>::SetNotMode( T mode )
{
    m_Mode &= (~mode);
}
template<class T>BOOL CFixedMode<T>::IsMode( T mode )
{
    return ( ( m_Mode & mode ) == mode ) ? TRUE : FALSE;
}
template<class T>CFixedMode<T>& CFixedMode<T>::operator =( const CFixedMode<T>& rFixedMode )
{
    if( typeid( m_Mode ) == typeid( rFixedMode.m_Mode ) )
        m_Mode = rFixedMode.m_Mode;
    return *this;
}

int _tmain(int argc, _TCHAR* argv[])
{
    CFixedMode<DWORD> Mode;
    DWORD rMode = 0x00000010;
    Mode.SetMode( rMode );

    CFixedMode<DWORD> Mode2;
    Mode2 = Mode;
    if( Mode2.IsMode( 0x00000010 ) )
    {
        //cout << Mode2.m_Mode; //c2248
        cout << "True" << endl;
    }

    typeid(Mode).before(typeid(CFixedMode<DWORD>));

    return 0;
}

Upvotes: 0

Views: 111

Answers (1)

Corbin
Corbin

Reputation: 33447

Private means that it's private to the class, not to instances of the class. Private is used to hide implementation details, so it makes sense that an object of the same type can access private members of other objects. Those other objects have the same implementation, so there's no point in hiding details.

By the way, your operator= should check for self assignment. (Or, as Chris pointed out, you could use the copy and swap idiom.) And, you don't need to check the types with typeid.

Upvotes: 1

Related Questions