0
class Link
{
private:
    string value;
    Link* succ;
    Link* prev;
public:
    Link(string v, Link* s = nullptr, Link* p = nullptr)
    : value(v), succ(s), prev(p) { }
Link* insert(Link* p)
{
    if(p == nullptr) return this;
    p->succ = this;
    if(this->prev) this->prev->succ = p->prev;
    p->prev = this->prev;
    this->prev = p;

    return p;
}
};

int main()
{
    Link* language = new Link{Link("C++", nullptr, nullptr)};
    language = language->insert(new Link("Python", language, nullptr));

    return 0;
}

In the book, programming principles and practice, there is a chapter where you implement a part of a list and here's the code.

In the above code, insert() takes Link* as an argument and uses -> to change what it's pointing at(Link* succ, prev) directly. But both succ and prev are private members of the class so I don't understand how it's possible for insert() to access them directly.

장용연
  • 9
  • 2
  • Answer this question -- Using your reasoning, how would/could `prev` and `succ` ever get changed if they're `private`? A class is allowed to change its internals. – PaulMcKenzie Dec 10 '18 at 03:55
  • Access restriction applies to the _class_, not to the _objects_. Any method in the class can access any field of any object in the class. It is code outside the class that has restricted access. – Frax Dec 10 '18 at 04:07
  • You are alway s friends of yourself (and your clones). https://stackoverflow.com/a/437507/14065 – Martin York Dec 10 '18 at 04:16
  • Semi-related note: `private` and `protected` only make it harder to make access mistakes. They can't stop deliberate attempts to circumvent the access restrictions and they do not make it impossible to screw up. – user4581301 Dec 10 '18 at 04:39

1 Answers1

0

In the above code, insert() takes Link* as an argument and uses -> to change what it's pointing at(Link* succ, prev) directly. But both succ and prev are private members of the class so I don't understand how it's possible for insert() to access them directly.

In a member function of a class, it is possible to access the private members of the class. Since insert() is a member function of the Link, you can access the private members of the class (prev and succ) in it. You can not only access the prev and succ of the implicit object, i.e. this->prev and this->succ, but you can access the prev and succ members of any instance of the class.

Form https://en.cppreference.com/w/cpp/language/access (emphasis mine):

A private member of a class can only be accessed by the members and friends of that class, regardless of whether the members are on the same or different instances:

R Sahu
  • 204,454
  • 14
  • 159
  • 270