Home > Backend Development > C++ > How Can C Objects of the Same Class Access Each Other's Private Member Variables?

How Can C Objects of the Same Class Access Each Other's Private Member Variables?

Susan Sarandon
Release: 2024-12-31 07:59:10
Original
402 people have browsed it

How Can C   Objects of the Same Class Access Each Other's Private Member Variables?

Why Can Objects of the Same Class Access Each Other's Private Data?

In C , objects of the same class can access each other's private data because access control operates on a per-class, not per-object, basis. This means that private data is only inaccessible to objects outside of the class.

For example, consider the following code:

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;
}
Copy after login

In this code, TrivialClass has a private member variable mData and a public member function getData that returns a reference to mData. When objects a and b are created, they are both able to access each other's private data through the getData function.

This is possible because C 's access control is based on the following rules:

  • Public members are accessible from anywhere.
  • Private members are accessible only from within the class.
  • Protected members are accessible from within the class and from derived classes.

Since mData is a private member, it should only be accessible from within the TrivialClass class. However, because access control is per-class, objects of the same class can still access each other's private members.

This behavior is not present in all programming languages. Some languages, such as Java, have true per-object access control, which means that objects of the same class cannot access each other's private data.

The above is the detailed content of How Can C Objects of the Same Class Access Each Other's Private Member Variables?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template