Warm tip: This article is reproduced from stackoverflow.com, please click
c++ private

Accessing private members c++

发布于 2020-03-31 22:58:47

In this code why can I access the private member of the object with no compiler error?

class Cents
{
private:
    int m_nCents;
public:
    Cents(int nCents=0)
    {
        m_nCents = nCents;
    }

    // Copy constructor
    Cents(const Cents &cSource)
    {
        m_nCents = cSource.m_nCents;
    }

    Cents& operator= (const Cents &cSource);

};

Cents& Cents::operator= (const Cents &cSource)
{

cSource.m_nCents is private why can I do the following:

    m_nCents = cSource.m_nCents;

    // return the existing object
    return *this;
}
Questioner
elios264
Viewed
33
Oliver Charlesworth 2011-12-18 03:58

Because private means "visible accessible to the class", not "visible accessible to the object".