c++boostshared-ptrfriendboost-smart-ptr

class not being recognized as friend


I have two classes say foo and bar. The constructor of foo is private so as to only allow the bar class to instantiate it.

// foo.h   
class foo
{
  friend class bar;
private:
  foo()
  {}
};

// bar.h
class bar
{
public:
  bar()
  {
    foo* f = new foo();
  } 
};

Also I am using boost::shared_ptr however for simplicity I did not mention it here

However when I attempt to build the program I get the error

In instantiation of ‘typename boost::detail::sp_if_not_array::type boost::make_shared() [with T = bar; typename boost::detail::sp_if_not_array::type = boost::shared_ptr]’:| /home/..../Projects/CodeBlocks/../bar.cpp|18|required from here| /home/..../Projects/CodeBlocks/../foo.h|23|error: ‘foo::foo()’ is private| ||=== Build finished: 1 errors, 2 warnings (0 minutes, 5 seconds) ===|

Is it because bar.h gets built first? If so, any suggestions on how to fix this?


Solution

  • I am using boost::shared_ptr however for simplicity I did not mention it here

    Ironically, that is the very thing that's making your code fail to compile. Without it, the example you've shown compiles without errors.

    The problem is that you're trying to use boost::make_shared to create the shared_ptr. This will lead to make_shared attempting to construct a foo, which of course fails, because you've declared bar to be a friend of foo's, but make_shared isn't a friend.

    Use the shared_ptr constructor directly instead, and pass it a pointer to a foo object that has been allocated by bar.

    Live demo


    Note that declaring boost::make_shared as a friend is not a reliable solution either because it may delegate the actual construction to some other function.