Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing private members c++

Tags:

c++

private

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;
}
like image 350
elios264 Avatar asked Dec 13 '22 07:12

elios264


1 Answers

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

like image 144
Oliver Charlesworth Avatar answered Dec 30 '22 01:12

Oliver Charlesworth