MistyD
MistyD

Reputation: 17233

Constructor(method) not being accepted as a friend

I currently have something like this. I would like to only allow the bar class to create an instance of the foo class so I have made it a friend of foo and made the constructor of fooprivate.

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


bar.h
#include "foo.h"
class bar
{
  private:
  boost::shared_ptr<foo> f;
  public:
  bar()
  {
    f = boost::shared_ptr<foo>(new foo());
  } 
}

The above works perfectly fine. However since the private member of the foo class is only being used in the constructor of the bar class (for instantiating). I would like to restrict private accessibility to only the constructor of the bar class so I decided to replace

friend class bar;

with this

friend bar::bar();

This does not work as the error messages says that bar is an incomplete type (Which I believe means that it cant find bar). Any suggestions on how to fix this problem ?

Upvotes: 0

Views: 85

Answers (1)

TAS
TAS

Reputation: 2079

My first suggestion would be to look at changing the design to use a factory method to create foo. Either as a static member function or as a free function.

But in the very rare cases that this is not an option the following code illustrates how it can be done.

bar.h

#include <boost/shared_ptr.hpp>

#ifndef BAR_H_
#define BAR_H_

class foo;

class bar {
private:
    boost::shared_ptr<foo> f;

public:
    bar();
};

#endif

foo.h

#include "bar.h"

#ifndef FOO_H_
#define FOO_H_

class foo {
    friend bar::bar();
private:
    foo() {}
};

#endif

bar.cpp

#include "bar.h"
#include "foo.h"

bar::bar() : f{ new foo() } 
{}

Upvotes: 1

Related Questions