If I have a subclass which should only be instantiated by its parent class, is friend
the appropriate method for accessing the constructor of the private or protected class?
To clarify, there are already questions where this is proposed as the answer. My question is specifically regarding whether this is the only answer and, if not, whether it is the most appropriate for this situation.
Example:
class Class_A {
public:
class Class_B {
// Adding 'friend' keyword here
friend class Class_A;
int _value;
Class_B(
int value)
:
_value(value)
{
}
};
protected:
static Class_A::Class_B createB(
int value)
{
return Class_B(value);
}
};
Credit goes to @Angew for correcting the first version of this answer. Here comes the update:
You are actually using the wrong term: Class_B
is not a subclass of Class_B
. The correct term is : nested class. The relationship implied by declaring one class inside another is the following one:
The nested class is a member of the enclosing one, and thus has the same access rights as a member (the nested class is basically an implicit friend of the enclosing class).
I.e. the nested class has access to protected and private members of the enclosing class, but not the other way around. Thus if you want to call a private or protected method (e.g. constructor) making them friends is the way to go.