Terminology or name required - c++

In many C++ source codes I see that while designing a class that might be sub-classed there's a forward declaration or reference to another similarly named class with a private or Private appended to the end of the original class name. For example in Qt there's a class named QGraphicsItem and in the beginning of the header file there's a forward declaration of QGraphicsItemPrivate. I tried looking in design pattern names and searched google trying to see if I can find what such design technique or method is called but It didn't yield any results. What's the name of this approach? What is / are the benefit(s)?

Sounds like the pimpl idiom. It goes by other names too, e.g., cheshire cat.
e.g.,
class FooPrivate;
class Foo
{
public:
Foo();
~Foo();
int GetInt();
private:
FooPrivate* implPtr;
};
in implementation file,
class FooPrivate
{
public:
int x = 0;
};
Foo::Foo() : implPtr(new FooPrivate()) {}
Foo::~Foo() { delete implPtr; }
int Foo::GetInt()
{
return implPtr->x;
}
It is used to hide implementation details of Foo. All data members and private methods are stored in Private. This means a change in the implementation does not need a recompile of every cpp file using Foo.
In the Qt source it is in qgraphicsitem_p.h. You can see it only stores data members and other implementation details.

I think there's a lot of your questions explained here: The Pimpl Idiom in practice.
But well, as you're explicitly asking for another answer:
"What's the name of this approach?"
It's widely called the Pimpl idiom, there are other (maybe more serious) equivalent terms in use, like e.g. opaque pointer).
The pattern generally looks like this:
A.h:
class AImpl;
class A {
public:
A();
~A();
void foo();
void bar();
private:
AImpl* pimpl;
};
A.cpp:
// Changing the following code won't have impact for need to recompile
// external dependants
// *******************************************************************
// * Closed black box *
// *******************************************************************
struct AImpl {
void foo();
void bar();
};
// *******************************************************************
// * lengthy implementation likely to change internally goes *
// * here *
// *******************************************************************
void AImpl::foo() {
}
void AImpl::bar() {
}
// * /Closed black box *
// *******************************************************************
// The public interface implementation just delegates to the
// internal one:
A::A() : pimpl(new AImpl()) {
}
A::~A() {
delete pimpl;
}
void A::foo() {
pimpl->foo();
}
void A::bar() {
pimpl->bar();
}
"What is / are the benefit(s)?"
Any code including A.h will just refer to the public interface, and doesn't need to be recompiled due to changes made in the internal implementation of AImpl.
That's a big improvement, to achieve modularization and implementation privacy.

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).

Optional class members without runtime overhead

I have the following very general problem that I have not found a satisfying solution to yet:
So I want to have two classes A and AData that are basically identical except that the latter has an additional attribute data and each of the classes supports a function foo(), which is different because it depends on the existence of the additional data.
The stupid solution is to copy the entire class and change it slightly, but that leads to code duplication and is hard to maintain. Using std::optional or a pointer lead to additional checks and therefore runtime overhead, right?
My question is whether there is a way to get the same runtime performance as just copying the code without actual code duplication? My current solution is to make AData a derived class and declare it as friend of A and then override the virtual function foo(), but I do not like this approach due to the use of friend.
You can use static polymorphism and curiosly recurring template pattern.
Both A and AData provide foo() but behaviour is class-specfic through doFoo(). Also not using virtual dispatch avoids runtime overhead of vtable lookup.
template <typename TData>
class Abase
{
public:
void foo()
{
static_cast<TData*>(this)->doFoo();
}
};
class A : public Abase<A>
{
friend ABase<A>;
void doFoo() { cout << "A::foo()\n"; }
};
class AData : public Abase<AData>
{
friend Abase<AData>;
int someDataMember;
void doFoo() { cout << "AData::foo()\n"; /*... use someDataMember ... */}
};
Live
Why not use composition:
class A
{
public:
void foo() { /*...*/ }
};
class AData
{
A a;
int someDataMember;
public:
void foo() { /*... use someDataMember ...*/ }
};

Hiding specific implementation of C++ interface

I'm relatively new to the more advanced C++ features... So keep that in mind ;)
I have recently defined an Interface to some class, consisting, of course, of only pure virtual functions.
Then, I implemented a specific version of that interface in separate files.
The question is... How do I invoke the specific implementation of that Interface on the user-end side, without revealing the internals of that specific implementation?
So if I have an Interface.h header file that looks like this:
class Interface
{
public:
Interface(){};
virtual ~Interface(){};
virtual void InterfaceMethod() = 0;
}
Then, a specific Implementation.h header file that looks like this:
class Implementation : public Interface
{
public:
Implementation(){};
virtual ~Implementation(){};
void InterfaceMethod();
void ImplementationSpecificMethod();
}
Finally, under main, I have:
int main()
{
Interface *pInterface = new Implementation();
// some code
delete pInterface;
return 0;
}
How can I do something like this, without revealing the details of Implementation.h, from "main"? Isn't there a way to tell "main"... Hey, "Implementation" is just a type of "Interface"; and keep everything else in a separate library?
I know this must be a duplicate question... But I couldn't find a clear answer to this.
Thanks for the help!
You can use a factory.
Header:
struct Abstract
{
virtual void foo() = 0;
}
Abstract* create();
Source:
struct Concrete : public Abstract
{
void foo() { /* code here*/ }
}
Abstract* create()
{
return new Concrete();
}
Although the factory solution seems to fit better the OP question, a version using the PIMPL idiom can address the same issue too.
While both versions incur in an indirect call through a pointer, the PIMPL version manages to avoid the virtual interface at the expenses of being more contrived.
Header file:
class Interface
{
struct Implementation;
std::unique_ptr< Implementation > m_impl;
public:
Interface();
~Interface();
void InterfaceMethod();
};
Implementation file:
class Interface::Implementation
{
public:
void ImplementationSpecificMethod()
{
std::cout << "ImplementationSpecificMethod()\n";
}
};
Interface::Interface()
: m_impl( std::make_unique< Interface::Implementation >( ) )
{ }
Interface::~Interface() = default;
void Interface::InterfaceMethod( )
{
m_impl->ImplementationSpecificMethod();
}
Main file:
int main()
{
Interface i;
i.InterfaceMethod(); // > ImplementationSpecificMethod()
}
See it online.
You can hide some of the inner details (privates) of your Implementation class from easy view in the header file by using something like PIMPL to conceal the implementation details in the .cpp file.
See Is the pImpl idiom really used in practice? for more discussion of the pimpl idiom.

Multiple public/private keyword in class definition

I have seen multiple public and private keywords in a class definition, like the example below:
class myClass
{
public:
void func1(){}
public:
void func2(){}
private:
int x;
int y;
private:
int z;
int baz;
};
What is the practical use of this (if any)? Is there any situation in which this could be useful?
Is there any situation in which this could be useful?
I can think of a situation where it would be very problematic otherwise:
class myClass
{
public:
void func1(){}
public:
void func2(){}
COORDINATES; // <-- Note the macro here!
private:
int z;
int baz;
};
which, after the expansion of the COORDINATES macro, becomes:
class myClass
{
public:
void func1(){}
public:
void func2(){}
private:
int x;
int y;
private:
int z;
int baz;
};
If multiple private / public keywords weren't allowed, it would be very painful to do it. Although using macros isn't good practice; neither is introducing access modifiers silently for all the members appearing after the macro. Nevertheless, it could be useful for RAD tools generating C++ source code.
I can only guess why you see that in human written classes. My guess is that it is poor coding; the writer probably wanted to express that a chunk of data belongs together and / or wanted to be able to move up and down those chunks within the class definition, together with the corresponding access modifier (private/protected/public).
I'll go one step farther from my comment for this answer, with a snippet of code.
class myClass {
// initializers etc
public:
myClass();
~myClass();
// signal processing
public:
void modifyClass();
private:
float signalValue;
// other class responsibilities
public:
void doWork();
private:
void workHelper();
};
and so on. I wouldn't say this is a solid DESIGN for the class, but it's a good way to show the different capabilities of a class.
Another use is when you want to have a specific destruction order. Lets consider two cases:
Bad case
// Auxiliary class
Class StorageCleaner {
public:
StorageCleaner(ExternalStorage* storage) : storage_(storage);
~StorageCleaner() { storage_->DeleteEverything(); }
private:
ExternalStorage* const storage_; // Not owned
}
// Class with bad declaration order
Class ExternalStorageWrapper {
public:
ExternalStorageWrapper(ExternalStorage* storage) : cleaner_(storage) {
pointer_to_storage_.reset(storage);
}
const StorageCleaner cleaner_;
private:
std::unique_ptr<ExternalStorage> pointer_to_storage_;
// Other data which should be private
int other_int;
string other_string;
....
};
What happens when existing ExternalStorageWrapper object goes out of scope?
The ExternalStorageWrapper destructor will first
destroy other data
Then it will destroy external storage pointed by pointer_to_external_storage_ (because fields are destroyed in reversed declaration order).
Then it will attempt to destroy cleaner_
But cleaner inside its own destructor attempts to manipulate external storage, which has already been destroyed!
Good case
// Class StorageCleaner same as before
...
// Class with better declaration order
Class ExternalStorageWrapper {
private:
std::unique_ptr<ExternalStorage> pointer_to_storage_;
public:
ExternalStorageWrapper(ExternalStorage* storage) : cleaner_(storage) {
pointer_to_storage_.reset(storage);
}
const StorageCleaner cleaner_;
private:
// Other data which should be private
int other_int;
string other_string;
....
};
What happens in this case when existing ExternalStorageWrapper object goes out of scope?
The ExternalStorageWrapper destructor will first destroy other data.
Then it will attempt to destroy cleaner_. Cleaner will DeleteEverything() from storage using storage_ pointer to still existing storage.
Finally, storage gets destroyed through pointer_to_storage_.
I actually had to debug such problem in a company, so although rare, this peculiar case is possible to occur.
One use case I encounter is for the clarity. As shown in the example below, class1 inherits base class which contains a pure virtual function that class1 needs to implement. To indicate that method1 in class1 is coming from some other class class1 inherits from (e.g. base) instead of class1's own function, we use another public to make this point clear:
class base {
public:
virtual void method1() = 0;
}
class class1: base {
public:
myOwnMethod1();
myOwnMethod2();
public: /* base interface */
method1();
Just finished reading those examples. Hopefully this one could contribute on how useful multiple keyword definition is.
We don't quite need to assume much since this is my current problem as of now but consume the following:
class IOHandler {
public:
enum COLOR_DEFINITIONS : unsigned char
{
BLACK,
DARK_ER_BLUE,
DARK_GREEN,
DARK_SKY_BLUE,
DARK_RED,
DARK_PINK,
DARK_YELLOW,
DARK_WHITE,
DARK_GREY,
DARK_BLUE,
BRIGHT_GREEN,
BRIGHT_SKY_BLUE,
BRIGHT_RED,
BRIGHT_PINK,
BRIGHT_YELLOW,
BRIGHT_WHITE
};
template <typename dtEX>
void showOutputEx(dtEX literalOutput, _COLOR_OUTPUT textColorSet = {COLOR_DEFINITIONS::BRIGHT_WHITE , COLOR_DEFINITIONS::BRIGHT_YELLOW}, bool appendOutputType = true, OUTPUT_TYPE levelOutput = OUTPUT_TYPE::OUTPUT_NORMAL, EMBRACE_TYPE embraceOutputType = EMBRACE_TYPE::EMBRACE_OUTPUT_LEVEL, ...);
// ! ^^^^^^^^^^^^^^ Doesn't detect the struct being referenced at which is at below.
private:
typedef struct colorProps // This is the struct that the public function where trying to get referenced at but failed to do so.
{
unsigned char C_BG = 0,
C_FG = 0;
} _COLOR_OUTPUT;
};
The error code.
identifier "_COLOR_OUTPUT" is undefined.
At this point, my intelliSense keep complaining that _COLOR_OUTPUT is undefined within public class scope.
The most probable solution is to put the struct inside public scope instead of private scope.
But I don't want to.
The reason this happens was due to the compiler reads the file from top to bottom. Anything that is declared
that requires reference should be on top and that should resolve the issue. Since I don't want to make things messed up by putting all private class functions and variables
on top. I should just declare another specifier on the top so that any public function requiring some reference might see it ahead.
So the solution is the following: (Is to move all referrable variables and struct on top of the class so that any private and public function argument reference is being recognized.)
class IOHandler {
// Private Class Scope for Variables and Structure
private:
typedef struct colorProps // This is the struct we move at the top for recognizing references.
{
unsigned char C_BG = 0,
C_FG = 0;
} _COLOR_OUTPUT;
public:
enum COLOR_DEFINITIONS : unsigned char
{
BLACK,
DARK_ER_BLUE,
DARK_GREEN,
DARK_SKY_BLUE,
DARK_RED,
DARK_PINK,
DARK_YELLOW,
DARK_WHITE,
DARK_GREY,
DARK_BLUE,
BRIGHT_GREEN,
BRIGHT_SKY_BLUE,
BRIGHT_RED,
BRIGHT_PINK,
BRIGHT_YELLOW,
BRIGHT_WHITE
};
template <typename dtEX>
void showOutputEx(dtEX literalOutput, _COLOR_OUTPUT textColorSet = {COLOR_DEFINITIONS::BRIGHT_WHITE , COLOR_DEFINITIONS::BRIGHT_YELLOW}, bool appendOutputType = true, OUTPUT_TYPE levelOutput = OUTPUT_TYPE::OUTPUT_NORMAL, EMBRACE_TYPE embraceOutputType = EMBRACE_TYPE::EMBRACE_OUTPUT_LEVEL, ...);
// ! ^^^^^^^^^^^^^^ Now recognizable reference.
private:
... // Any other functions, excerpt.
};

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).