Access to C ++ Private Members

In this code, why can I access the private member of an object without a 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; } 
+4
source share
2 answers

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

+9
source

You can access private members from member functions / constructors / destructor / freinds class. This is class-based accessibility, not object accessibility.

+4
source

Source: https://habr.com/ru/post/1386856/


All Articles