Friend function is unable to construct a unique pointer of the class - c++

I have a certain design strategy where the constructor of my class is private and can only be constructed by friends of the class. Inside the friend function, I am trying to create a unique_pointer of my class using std::make_uniquebut it doesn't compile. My VC12 compiler complains
c:\program files (x86)\microsoft visual studio
12.0\vc\include\memory(1639): error C2248: 'Spam::Spam' : cannot access private member declared in class 'Spam'
The relevant code which fails during compilation is as follows
#include <memory>
class Spam {
public:
friend void Foo();
private:
Spam(int mem) :mem(mem) {}
int mem;
};
void Foo() {
std::unique_ptr<Spam> spam = std::make_unique<Spam>(10);
}
Why am I not able to compile?

In your case the function make_unique is trying to create an instance of Spam and that function is not a friend. Calling a non-friend function from inside a friend function does not imbue the non-friend function with friend status.
To solve this you can write in Foo:
std::unique_ptr<Spam> spam(new Spam(10));

Here is another approach I've seen used, apparently known as the passkey idiom : have the public constructor require a private access token.
class Spam {
struct Token {};
friend void Foo();
public:
Spam(Token, int mem) : mem(mem) {}
private:
int mem;
};
void Foo() {
std::unique_ptr<Spam> spam = std::make_unique<Spam>(Spam::Token{}, 10);
}
void Bar() {
// error: 'Spam::Token Spam::token' is private
// std::unique_ptr<Spam> spam = std::make_unique<Spam>(Spam::Token{}, 10);
}

Why am I not able to compile?
You are unable to compile because make_unique is not a friend of Spam.
An alternative solution to making make_unique a friend is to move the creation of the unique_ptr into Spam.
class Spam {
...
private:
Spam(int) {}
static unique_ptr<Spam> create( int i )
{ return std::unique_ptr<Spam>( new Spam(i) ); }
};
and then have Foo call that instead.
void Foo() {
std::unique_ptr<Spam> spam = Spam::create(10);
...
}

In your example, Foo() is a friend, but it isn't the function that's creating the Spam - make_unique is internally calling new Spam itself. The simple fix is to just have Foo() actually construct the Spam directly:
void Foo() {
std::unique_ptr<Spam> spam(new Spam(10));
}

Related

Exposing only a single method of a class to another class but having it inaccessible everywhere else [duplicate]

Suppose I have three C++ classes FooA, FooB and FooC.
FooA has an member function named Hello, I want to call this function in class FooB, but I don't want class FooC be able to call it. The best way I can figure out to realize this is to declare FooB as a friend class of FooA. But as long as I do this, all FooA's private and protected members will be exposed which is quite unacceptable to me.
So, I wanna know if there is any mechanism in C++(03 or 11) better than friend class which can solve this dilemma.
And I assume it will be nice if the following syntax is possible:
class FooA
{
private friend class FooB:
void Hello();
void Hello2();
private:
void Hello3();
int m_iData;
};
class FooB
{
void fun()
{
FooA objA;
objA.Hello() // right
objA.Hello2() // right
objA.Hello3() // compile error
ojbA.m_iData = 0; // compile error
}
};
class FooC
{
void fun()
{
FooA objA;
objA.Hello() // compile error
objA.Hello2() // compile error
objA.Hello3() // compile error
ojbA.m_iData = 0; // compile error
}
};
I think you can use Attorney-Client here.
In your case example should be like this
class FooA
{
private:
void Hello();
void Hello2();
void Hello3();
int m_iData;
friend class Client;
};
class Client
{
private:
static void Hello(FooA& obj)
{
obj.Hello();
}
static void Hello2(FooA& obj)
{
obj.Hello2();
}
friend class FooB;
};
class FooB
{
void fun()
{
FooA objA;
Client::Hello(objA); // right
Client::Hello2(objA); // right
//objA.Hello3() // compile error
//ojbA.m_iData = 0; // compile error
}
};
class FooC
{
void fun()
{
/*FooA objA;
objA.Hello() // compile error
objA.Hello2() // compile error
objA.Hello3() // compile error
ojbA.m_iData = 0; // compile error*/
}
};
There's nothing to make a class a friend of one specific function, but you can make FooB a friend of a "key" class with private constructor, and then have FooA::Hello take that class as an ignored parameter. FooC will be unable to provide the parameter and hence can't call Hello:
Is this key-oriented access-protection pattern a known idiom?
You can partially expose a class's interfaces to a specified client by inherit it from an interface class.
class FooA_for_FooB
{
public:
virtual void Hello() = 0;
virtual void Hello2() = 0;
};
class FooA : public FooA_for_FooB
{
private: /* make them private */
void Hello() override;
void Hello2() override;
private:
void Hello3();
int m_iData;
};
class FooB
{
void fun()
{
FooA objA;
FooA_for_FooB &r = objA;
r.Hello() // right
r.Hello2() // right
objA.Hello3() // compile error
objA.m_iData = 0; // compile error
}
};
class FooC
{
void fun()
{
FooA objA;
objA.Hello() // compile error
objA.Hello2() // compile error
objA.Hello3() // compile error
objA.m_iData = 0; // compile error
}
};
Here access control is enhanced by the base class FooA_for_FooB. By a reference of type FooA_for_FooB, FooB can access the members defined within FooA_for_FooB. However, FooC cannot access those members since they have been override as private members in FooA. Your purpose can be achieved by not using the type FooA_for_FooB within FooC, or any other places except FooB, which can be kept without paying much attention.
This approach needs no friend, making things simple.
A similar thing can be done by making everything private in a base class, and selectively wrap-and-expose some of the members as public in the derived class. This approach may sometimes require ugly downcast, though. (Because the base class will become the "currency" among the whole program.)
No, and this is not really a limitation. To my mind, the limitation is that friend — a blunt weapon for hacking around design flaws — exists in the first place.
Your class FooA has no business knowing about FooB and FooC and "which one should be able to use it". It should have a public interface, and not care who can use it. That's the point of the interface! Calling functions within that interface should always leave the FooA in a nice, safe, happy, consistent state.
And if your concern is that you might accidentally use the FooA interface from somewhere you didn't mean to, well, simply don't do that; C++ is not a language suited to protecting against these kinds of user errors. Your test coverage should suffice in this case.
Strictly speaking, I'm sure you can obtain the functionality you're after with some ghastly complicated "design pattern" but, honestly, I wouldn't bother.
If this is a problem for the semantics of your program's design, then I politely suggest that your design has a flaw.
The safest solution is to use another class as the "go-between" for your two classes, rather than make one of them a friend. One way to do this is suggested in the answer by #ForEveR, but you can also do some searching about proxy classes and other design patterns that can apply.
You'll need inheritance. Try this:
// _ClassA.h
class _ClassA
{
friend class ClassA;
private:
//all your private methods here, accessible only from ClassA and _ClassA.
}
// ClassA.h
class ClassA: _ClassA
{
friend class ClassB;
private:
//all_your_methods
}
This way you have:
ClassB is the only one to be able to use ClassA.
ClassB cannot access _ClassA methods, that are private.
The whole idea of friend is to expose your class to a friend.
There are 2 ways you could be more specific about what you expose:
Inherit from FooA, that way only protected and public methods are exposed.
Only befriend a certain method, that way only that method will have access:
.
friend void FooB::fun();
You can hide private members in a base class, and then make FooA a child and friend of that base class (very touching).
// allows us to hide private members from friends of FooA,
// but still allows FooA itself to access them.
class PrivateFooA
{
private:
friend class FooA;
// only allow FooA to derive from this class
PrivateFooA() {};
// hidden from friends of FooA
void Hello3();
int m_iData;
};
// this class hides some of its private members from friend classes
class FooA : public PrivateFooA
{
private:
// give FooB access to private methods
friend class FooB;
void Hello();
void Hello2();
};
class FooB
{
void fun()
{
FooA objA;
objA.Hello(); // right
objA.Hello2(); // right
objA.Hello3(); // compile error
ojbA.m_iData = 0; // compile error
}
};
class FooC
{
void fun()
{
FooA objA;
objA.Hello(); // compile error
objA.Hello2(); // compile error
objA.Hello3(); // compile error
ojbA.m_iData = 0; // compile error
}
};
Anything you want to hide from FooB can be put into PrivateFooA (must be a private member), and everything else can be put directly into FooA. FooA will be able to access everything in PrivateFooA just like its own members.
This is more of an expansion of user3737631's answer, but I think it's worth posting because it includes the classes from the OP, the private constructor in PrivateFooA, and some additional comments that I thought would be helpful.
I had to do this recently and I didn't like the way these solutions leave a class type dangling around in the current namespace with essentially no purpose. If you REALLY do just want this functionality available to a single class then I would use a different pattern than those mentioned.
class Safety {
protected:
std::string _Text="";
public:
Safety(const std::string& initial_text) {
_Text=initial_text;
}
void Print(const std::string& test) {
std::cout<<test<<" Value: "<<_Text<<std::endl;
}
};
class SafetyManager {
protected:
// Use a nested class to provide any additional functionality to
// Safety that you want with protected level access. By declaring
// it here this code only belongs to this class. Also, this method
// doesn't require Safety to inherit from anything so you're only
// adding weight for the functionality you need when you need it.
// You need to be careful about how this class handles this object
// since it is really a Safety cast to a _Safety. You can't really
// add member data to this class but static data is ok.
class _Safety : Safety {
public:
void SetSafetyText(const std::string& new_text) {
_Text=std::string(new_text);
}
};
public:
static void SetSafetyText(Safety* obj, const std::string& new_text) {
if(obj==nullptr) throw "Bad pointer.";
_Safety& iobj=*(_Safety*)obj;
iobj.SetSafetyText(new_text);
}
};
Then in main (or anywhere else) you can't modify _Text through Safety but you can through SafetyManager (or it's descendants).
#include "Safety.h"
int main() {
Safety t("Hello World!");
t.Print("Initial");
SafetyManager::SetSafetyText(&t, "Brave New World!");
t.Print("Modified");
/*
t._Text; // not accessible
Safety::SetSafetyText(&t, "ERR");// doesn't exist
t.SetSafetyText(&t, "ERR"); // doesn't exist
_Safety _safety; // not accessible
SafetyManager::_Safety _safety; // not accessible
*/
}
Some would say that this follows better OOP practices than a friend class because it encapsulates the messy parts a little better and doesn't pass anything down the Safety chain of inheritance. You also don't need to modify the Safety class at all for this technique making it much more modular. These are probably the reasons why many newer languages allow for nested classes but almost nothing else has borrowed the friend concept even though this just adds functionality that is available only to a single class (and doesn't work if Safety is marked final or marked vital parts of it's code as private).

Unable to access members of including class from a polymorphic nested classes

A nested class Foo::Utility has access to another nested class Foo::Container even if the later is private. I am trying to extend this access to a polymorphic version UtilityPrint of Foo::Utility without success:
class Foo {
private:
class Container {};
public:
class Utility {
public:
virtual void action(Container &) = 0;
// works even if Container is private
};
Container container;
Utility * utility;
Foo(Utility * utility): container(), utility(utility) {};
void performAction() {
utility -> action(container);
}
};
// polymorphic nested class
// failed attempt
class UtilityPrint : Foo::Utility {
public:
virtual void action(Foo::Container &) {
/* Implementation */
// this does not work, because Foo::Container is private
}
};
Is there a correct way to achieve this, or is this a bad idea to begin with?
The error message I get is this:
error: ‘class Foo::Container’ is private
class Container {};
^
error: within this context
virtual void action(Foo::Container &) {
Also, Here is my reason for using this somewhat weird design:
I wanted a container and a polymorphic utility that does things to both the container and Foo. Since both container and utility would only be used within the context of Foo, I put the two classes into Foo.
EDIT: I can wrap the derived Utility in a derived Foo, and the code compiles:
class Foo {
protected:
class Container {};
public:
class Utility {
public:
virtual void action(Container &) = 0;
};
Container container;
Utility * utility;
Foo(Utility * utility): container(), utility(utility) {};
void performAction() {
utility -> action(container);
}
};
class FooPrint : public Foo {
public:
class Utility : Foo::Utility {
public:
virtual void action(Foo::Container &) {
/* Implementation */
}
};
};
This however introduces a wrapper class FooPrint which exists only for syntactic reasons and is (being a derived class!) never meant to be instantiated. I don't like this approach for this reason, but I can be very wrong on this regard.
Access is not inherited. This is more often brought up when discussing friends, but it applies here as well.
First, let's look at why Foo::Utility::action can access the private class Foo::Container. Actually, it's right there in the names. The Foo::Container can only be accessed by members of Foo, and members of Foo can be recognized when you write out their qualified names and that name starts with "Foo::".
In contrast, UtilityPrint is not a member of Foo. (In fact, it would be a huge security violation if someone could simply say "oh, yeah, I'm a member too!" and get access to your private information.) So while UtilityPrint has (protected) access to Foo::Utility, it does not have access to everything to which Foo::Utility has access.
If Foo::Utility desires to extend its access to classes derived from it, it would need to explicitly do so. One way to do this is by creating an alias.
class Utility {
protected:
using Container = Foo::Container; // Derived classes can access this.
public:
virtual void action(Container &) = 0;
virtual ~Utility() {} // <-- remember to properly support polymorphism
};
That still leaves open the question of whether or not this is good design. I would consider this a warning flag that something might be off, but not conclusively so. The question does not have enough context for me to make this sort of call. I would just give you the guideline that if you feel like you are circumventing a lot of language features (like private access), then maybe the design needs work.
I adopted this solution:
class Foo {
protected:
class Container {};
public:
class Utility {
protected:
typedef Container FooContainer;
public:
virtual void action(Container &) = 0;
};
Container container;
Utility * utility;
Foo(Utility * utility): container(), utility(utility) {};
void performAction() {
utility -> action(container);
}
};
class UtilityPrint : Foo::Utility {
public:
virtual void action(FooContainer &) {
/* implementation */
}
};
When the name FooContainer is introduced using typedef, accessibility is applied to that name only, with no regard of it actually referring to Foo::Container. This allows all derived Utility to reference Foo::Container by naming FooContainer.
I believe this also applies to using

static_assert : a certain function in Derive "must" hides Base's class function

I face a strange rare problem that I want to hide a Base class's function B::f1(int).
class B{
public: void f1(int){}
public: void f1(float){}
};
class C : public B{
public: void f1(int){
//static_assert(ASSERT_that_thisFunctionHidParentFunction,"");
//some rare ugly hacky stuff
}
public: void f1(char){
//static_assert(!ASSERT_that_thisFunctionHidParentFunction,"");
}
};
Everything works fine ; I just worry about maintainability.
I wish to make sure that a function C::f1(int) always hides B::f1(int).
If B::f1(int) happen to change signature in the future (e.g. to B::f1(int,int)),
I want some compile error to notify programmers that C::f1(int) should be changed to C::f1(int,int) as well.
In real world, my problematic function f1 doesn't have overload.
But for educational purpose, I wish to know how to solve it if there are overload too. (i.e. optional)
I love a cute solution like ASSERT_that_thisFunctionHidParentFunction in my code comment.
I don't mind MACRO.
My poor solution
I tried to typedef to force compile error, but it doesn't assert-fail in some case (MCVE-coliru), because int is automatically casted to B::f1(float).
class B{
public: void f1(int,int){}
public: void f1(float){}
};
class C : public B{
public: void f1(int){
using XXX=decltype(std::declval<B>().f1(std::declval<int>()));
//static_assert(ASSERT_that_thisFunctionHidParentFunction,"");
}
public: void f1(char){
//static_assert(!ASSERT_that_thisFunctionHidParentFunction,"");
}
};
int main() {
return 0;
}
You could check that the function pointers are different.
With MSVC 2019 and Clang 8 this worked for me, however GCC rejected it as "not a constant expression", so might need something different or a a runtime assert there. Not sure which is right in regards to the standard.
class B {
public:
void f1(int) {}
void f2(int) {}
void f3(int) {}
void f1(float) {}
};
class C : public B {
public:
void f1(int) {}
void f1(char) {}
void f3(int) {}
};
static_assert(&B::f1 != &C::f1); // Won't work because of the overloading, can static_cast to get the overload you want
static_assert(static_cast<void(B:: *)(int)>(&B::f1) != static_cast<void(C:: *)(int)>(&C::f1));
static_assert(static_cast<void(B:: *)(int)>(&B::f2) != static_cast<void(C:: *)(int)>(&C::f2)); // static assertion failed
static_assert(&B::f3 != &C::f3); // passes, no static_cast as not overloaded
Be very careful with hiding a member function in this way, as the base class is public and the method is not virtual. It can easily be cast and then the derived function is not called.
C *c = ...;
B *b = c; // Implicit
b->f1(5); // Calls B::f1, not C::f1
If possible it may be best to make the inheritance protected or private to avoid accidental casting.
The way I understand your question, it seems that you want to make sure that several implementation classes comply with a certain non-virtual concept.
template <typename Candidate>
struct ShipConcept
{
constexpr ShipConcept()
{
using ProtoFoo = void (Candidate::*)(int);
(void)static_cast<ProtoFoo>(&Candidate::foo);
// Other tests ...
}
};
struct Ship_A
: private ShipConcept<Ship_A>
{
Ship_A()
{
}
void foo(int, int);
void foo(float);
void foo(int); // (1)
};
You'll get compile-time error if line (1) isn't there.

Allowing a "friend" class to access only some private members

Suppose I have three C++ classes FooA, FooB and FooC.
FooA has an member function named Hello, I want to call this function in class FooB, but I don't want class FooC be able to call it. The best way I can figure out to realize this is to declare FooB as a friend class of FooA. But as long as I do this, all FooA's private and protected members will be exposed which is quite unacceptable to me.
So, I wanna know if there is any mechanism in C++(03 or 11) better than friend class which can solve this dilemma.
And I assume it will be nice if the following syntax is possible:
class FooA
{
private friend class FooB:
void Hello();
void Hello2();
private:
void Hello3();
int m_iData;
};
class FooB
{
void fun()
{
FooA objA;
objA.Hello() // right
objA.Hello2() // right
objA.Hello3() // compile error
ojbA.m_iData = 0; // compile error
}
};
class FooC
{
void fun()
{
FooA objA;
objA.Hello() // compile error
objA.Hello2() // compile error
objA.Hello3() // compile error
ojbA.m_iData = 0; // compile error
}
};
I think you can use Attorney-Client here.
In your case example should be like this
class FooA
{
private:
void Hello();
void Hello2();
void Hello3();
int m_iData;
friend class Client;
};
class Client
{
private:
static void Hello(FooA& obj)
{
obj.Hello();
}
static void Hello2(FooA& obj)
{
obj.Hello2();
}
friend class FooB;
};
class FooB
{
void fun()
{
FooA objA;
Client::Hello(objA); // right
Client::Hello2(objA); // right
//objA.Hello3() // compile error
//ojbA.m_iData = 0; // compile error
}
};
class FooC
{
void fun()
{
/*FooA objA;
objA.Hello() // compile error
objA.Hello2() // compile error
objA.Hello3() // compile error
ojbA.m_iData = 0; // compile error*/
}
};
There's nothing to make a class a friend of one specific function, but you can make FooB a friend of a "key" class with private constructor, and then have FooA::Hello take that class as an ignored parameter. FooC will be unable to provide the parameter and hence can't call Hello:
Is this key-oriented access-protection pattern a known idiom?
You can partially expose a class's interfaces to a specified client by inherit it from an interface class.
class FooA_for_FooB
{
public:
virtual void Hello() = 0;
virtual void Hello2() = 0;
};
class FooA : public FooA_for_FooB
{
private: /* make them private */
void Hello() override;
void Hello2() override;
private:
void Hello3();
int m_iData;
};
class FooB
{
void fun()
{
FooA objA;
FooA_for_FooB &r = objA;
r.Hello() // right
r.Hello2() // right
objA.Hello3() // compile error
objA.m_iData = 0; // compile error
}
};
class FooC
{
void fun()
{
FooA objA;
objA.Hello() // compile error
objA.Hello2() // compile error
objA.Hello3() // compile error
objA.m_iData = 0; // compile error
}
};
Here access control is enhanced by the base class FooA_for_FooB. By a reference of type FooA_for_FooB, FooB can access the members defined within FooA_for_FooB. However, FooC cannot access those members since they have been override as private members in FooA. Your purpose can be achieved by not using the type FooA_for_FooB within FooC, or any other places except FooB, which can be kept without paying much attention.
This approach needs no friend, making things simple.
A similar thing can be done by making everything private in a base class, and selectively wrap-and-expose some of the members as public in the derived class. This approach may sometimes require ugly downcast, though. (Because the base class will become the "currency" among the whole program.)
No, and this is not really a limitation. To my mind, the limitation is that friend — a blunt weapon for hacking around design flaws — exists in the first place.
Your class FooA has no business knowing about FooB and FooC and "which one should be able to use it". It should have a public interface, and not care who can use it. That's the point of the interface! Calling functions within that interface should always leave the FooA in a nice, safe, happy, consistent state.
And if your concern is that you might accidentally use the FooA interface from somewhere you didn't mean to, well, simply don't do that; C++ is not a language suited to protecting against these kinds of user errors. Your test coverage should suffice in this case.
Strictly speaking, I'm sure you can obtain the functionality you're after with some ghastly complicated "design pattern" but, honestly, I wouldn't bother.
If this is a problem for the semantics of your program's design, then I politely suggest that your design has a flaw.
The safest solution is to use another class as the "go-between" for your two classes, rather than make one of them a friend. One way to do this is suggested in the answer by #ForEveR, but you can also do some searching about proxy classes and other design patterns that can apply.
You'll need inheritance. Try this:
// _ClassA.h
class _ClassA
{
friend class ClassA;
private:
//all your private methods here, accessible only from ClassA and _ClassA.
}
// ClassA.h
class ClassA: _ClassA
{
friend class ClassB;
private:
//all_your_methods
}
This way you have:
ClassB is the only one to be able to use ClassA.
ClassB cannot access _ClassA methods, that are private.
The whole idea of friend is to expose your class to a friend.
There are 2 ways you could be more specific about what you expose:
Inherit from FooA, that way only protected and public methods are exposed.
Only befriend a certain method, that way only that method will have access:
.
friend void FooB::fun();
You can hide private members in a base class, and then make FooA a child and friend of that base class (very touching).
// allows us to hide private members from friends of FooA,
// but still allows FooA itself to access them.
class PrivateFooA
{
private:
friend class FooA;
// only allow FooA to derive from this class
PrivateFooA() {};
// hidden from friends of FooA
void Hello3();
int m_iData;
};
// this class hides some of its private members from friend classes
class FooA : public PrivateFooA
{
private:
// give FooB access to private methods
friend class FooB;
void Hello();
void Hello2();
};
class FooB
{
void fun()
{
FooA objA;
objA.Hello(); // right
objA.Hello2(); // right
objA.Hello3(); // compile error
ojbA.m_iData = 0; // compile error
}
};
class FooC
{
void fun()
{
FooA objA;
objA.Hello(); // compile error
objA.Hello2(); // compile error
objA.Hello3(); // compile error
ojbA.m_iData = 0; // compile error
}
};
Anything you want to hide from FooB can be put into PrivateFooA (must be a private member), and everything else can be put directly into FooA. FooA will be able to access everything in PrivateFooA just like its own members.
This is more of an expansion of user3737631's answer, but I think it's worth posting because it includes the classes from the OP, the private constructor in PrivateFooA, and some additional comments that I thought would be helpful.
I had to do this recently and I didn't like the way these solutions leave a class type dangling around in the current namespace with essentially no purpose. If you REALLY do just want this functionality available to a single class then I would use a different pattern than those mentioned.
class Safety {
protected:
std::string _Text="";
public:
Safety(const std::string& initial_text) {
_Text=initial_text;
}
void Print(const std::string& test) {
std::cout<<test<<" Value: "<<_Text<<std::endl;
}
};
class SafetyManager {
protected:
// Use a nested class to provide any additional functionality to
// Safety that you want with protected level access. By declaring
// it here this code only belongs to this class. Also, this method
// doesn't require Safety to inherit from anything so you're only
// adding weight for the functionality you need when you need it.
// You need to be careful about how this class handles this object
// since it is really a Safety cast to a _Safety. You can't really
// add member data to this class but static data is ok.
class _Safety : Safety {
public:
void SetSafetyText(const std::string& new_text) {
_Text=std::string(new_text);
}
};
public:
static void SetSafetyText(Safety* obj, const std::string& new_text) {
if(obj==nullptr) throw "Bad pointer.";
_Safety& iobj=*(_Safety*)obj;
iobj.SetSafetyText(new_text);
}
};
Then in main (or anywhere else) you can't modify _Text through Safety but you can through SafetyManager (or it's descendants).
#include "Safety.h"
int main() {
Safety t("Hello World!");
t.Print("Initial");
SafetyManager::SetSafetyText(&t, "Brave New World!");
t.Print("Modified");
/*
t._Text; // not accessible
Safety::SetSafetyText(&t, "ERR");// doesn't exist
t.SetSafetyText(&t, "ERR"); // doesn't exist
_Safety _safety; // not accessible
SafetyManager::_Safety _safety; // not accessible
*/
}
Some would say that this follows better OOP practices than a friend class because it encapsulates the messy parts a little better and doesn't pass anything down the Safety chain of inheritance. You also don't need to modify the Safety class at all for this technique making it much more modular. These are probably the reasons why many newer languages allow for nested classes but almost nothing else has borrowed the friend concept even though this just adds functionality that is available only to a single class (and doesn't work if Safety is marked final or marked vital parts of it's code as private).

C++ FAQ Lite Smart_Ptr Class Not Functioning?

I'm currently doing a lot of things on exception safety. (Herb Sutter's Exceptional C++, C++ FAQ Lite, etc)
In particular, I wanted to write and understand the reference counting example of C++ FAQ Lite, but I'm currently stuck on this part of the code:
class Smart_Ptr;
class Foo
{
private:
friend class Smart_Ptr;
unsigned int count_;
public:
static Smart_Ptr create() // Error here.
{
return new Foo();
}
private:
Foo()
: count_(0)
{ }
/* ... */
/* Smart_Ptr class initialized down here */
As you can see, I'm trying to use the Named Constructor Idiom to force the user not to create local variables of my Foo object. Essentially, this is exactly what is written in the C++ FAQ; I have merely changed Fred to Foo and FredPtr to Smart_Ptr, which I realize was a mistake because it's harder to see the connection now.
My compiler spits out the error:
error C2027: use of undefined type 'Smart_Ptr'
I'm not exactly sure why this is. Smart_Ptr is fully defined and a complete duplicate of the FAQ code. I have also copied the code in full, as is, and have received the same error.
End Crucial Part of Question
Since I keep mistakingly thinking I post 'enough' of the source code to debug the problem, and I keep ending up in the wrong, I will post the rest of the code here.
/* Foo.h */
class Smart_Ptr;
class Foo
{
private:
friend class Smart_Ptr;
unsigned int count_;
public:
static Smart_Ptr create()
{
return new Foo();
}
private:
Foo()
: count_(0)
{ }
};
class Smart_Ptr
{
private:
Foo *p_; // p_ is NEVER null
public:
Foo *operator-> () { return p_; }
Foo& operator* () { return *p_; }
Smart_Ptr(Foo *p)
: p_(p)
{
++p_->count_;
}
~Smart_Ptr()
{
if (--p_->count_ == 0)
delete p_;
}
Smart_Ptr(Smart_Ptr const& p)
: p_(p.p_)
{
++p_->count_;
}
Smart_Ptr& operator= (Smart_Ptr const& p)
{
Foo *const old = p_;
p_ = p.p_;
++p_->count_;
if (--old->count_ == 0)
delete old;
return *this;
}
};
You can't write a function that returns Smart_Ptr by value, until Smart_Ptr is defined. A forward declaration isn't enough.
The code you link to contains the comment, // Defined below class FredPtr {...};, but you have defined the create function in the Foo class definition. If you look closely at the code after "the changes to class Fred would be:", you'll see that create is only declared in the class: it's defined later, by the following code:
inline FredPtr Fred::create() { return new Fred(); }
All you need is to do the same.