0

In book "C++ Concurrency in Action: Practical Multithreading" by Anthony Williams I found this code example

template<typename T> class threadsafe_stack { private: std::stack<T> data; mutable std::mutex m; public: threadsafe_stack(){} threadsafe_stack (const threadsafe_stack& other) { std::lock_guard<<std::mutex> lock(other.m); ... rest of the code. 

(in my version of the book this is listing 3.5)

Why I have direct access to other object private data (mutex m in this case)? Maybe I missed something or maybe this is a typo (I have Russian version of the book and there is no errata)

Thanks in advance.

Dmitry.

2
  • 4
    Nothing special, you can access private members from other instances within the same class. Commented Jul 8, 2016 at 22:29
  • What @πάνταῥεῖ said. Instances can access private data in other instances of the same class. If you think about it - this is the only way copy constructors could be made to work (not to mention operator=, etc etc). Commented Jul 8, 2016 at 22:31

1 Answer 1

1

This is perfectly normal, the private declaration only pertains to child classes and uses of this class, not to other instances of the same class. In fact this is how things like operator= work.

eg.

class A { private: int b; public: A() : b(rand()) {} A& operator=(const A& rhs) { b = rhs.b; } }; class B : public A { public: void set(int newB) { b = newB; // Not ok. } }; int main() { A a, aa; a.b = 5; // Not ok. a = aa; // Ok. } 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks alot. looks like this aspect completly fllew out of my head.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.