0

I am implementing my own SharedPtr and WeakPtr and there are many methods where I need access to private members of SharedPtr from WeakPtr's methods. For example:

template<typename Resource>
WeakPtr<Resource>::WeakPtr(const SharedPtr<Resource>& rhs)
{
    //how can i get access to private members of rhs there?
    //only way is make them public?
    //I need something like this:
    resource = rhs.resource;
    control_block = rhs.control_block;
}
ADV
  • 179
  • 9
  • 2
    If you "need" access to private data, then the data isn't private by-definition. It must be either made public or the requesting client be made a friend. – WhozCraig Oct 14 '20 at 16:54
  • 2
    Classes which are very close related may make each other a `friend`. – Scheff's Cat Oct 14 '20 at 16:54
  • 1
    Does this answer your question? [When should you use friend classes?](https://stackoverflow.com/questions/6718209/when-should-you-use-friend-classes) (It's more related to design decision than to mechanism itself, but I guess it could answer the question.) – Yksisarvinen Oct 14 '20 at 16:56
  • 5
    If you're already working on templates and smart pointer implementations, then you should already grasp the basics of C++, and know about `friend` declarations. If you don't, then take a few steps back, invest in [some good books](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list), and start over from the beginning. – Some programmer dude Oct 14 '20 at 16:59

0 Answers0