Why do objects of the same class have access to ea

2019-01-01 08:45发布

Why do objects of the same class have access to each other's private data?

class TrivialClass {
public: 
  TrivialClass(const std::string& data) :
    mData(data) {};

  const std::string& getData(const TrivialClass& rhs) const {
    return rhs.mData;
  };

private:
  std::string mData;
};

int main() {
  TrivialClass a("fish");
  TrivialClass b("heads");

  std::cout << "b via a = " << a.getData(b) << std::endl;
  return 0;
}

This codes works. It is perfectly possible for object a to access private data from object b and return it. Why should this be so? I would think that private data is private. (I started out by trying to understand copy constructors in the pimpl idiom, but then I discovered that I didn't even understand this simple situation.)

7条回答
刘海飞了
2楼-- · 2019-01-01 09:32

Private data remains private until somebody who has access to it reveal it to other.

This concept applies to other situation too, such as :

class cMyClass
{
public:
   // ...
   // omitted for clarity
   // ...

   void Withdraw(int iAmount)
   {
      iTheSecretVault -= iAmount;
   }

private:
   int iTheSecretVault;
};

How could anyone withdraw the money ? :)

查看更多
登录 后发表回答