Remove friend class dependency in the following case - c++

class foo
{
bar b;
someFunction()
{
b.alphaObj->someFunctionOfAlpha();
}
};
class bar
{
friend class foo;
// many more friends
private:
alpha *alphaObj;
};
How do I remove the friend dependency without exposing the private members with getters and setters.
I understand friend classes could help in enhancing encapsulation but there are a lot of friend classes defined in my class exposing the private members to all. Hence I am thinking of a better approach and any help is appreciated.

Independent of your friend issue, being required to write this
b.alphaObj->someFunctionOfAlpha();
is not the best design. You should rather call (*):
b.someFunctionOfAlpha();
Now it is also obvious how to remove the friends:
class bar
{
public:
void someFunctionOfAlpha() { alphaObj->someFunctionOfAlpha(); }
private:
alpha *alphaObj;
};
(*) This guideline has a name, I just cannot find it at the moment. In general, calling a method should be like: "Do that!". Calling a method should not be like "Show me your internals so I can do what I want".

Related

How to expose different part of a class interface to different classes without any runtime cost? [duplicate]

This question already has answers here:
Allowing a "friend" class to access only some private members
(9 answers)
Closed 5 years ago.
Suppose that I have these classes:
class Bar;
class Foo {
private:
// stuff here
public:
void methodForClassBar();
};
What I want to do is make methodForClassBar private in a way that class Bar still be able to call it. But I don't want class Bar to be able to access any other private members of Foo.
My current solution is this: put methodForClassBar into private, and create an accessor class (FooInterfaceToClassBar, this can only be accessed by Bar), which is a friend to Foo. So with this accessor class, I can call methodForClassBar:
class FooInterfaceToClassBar;
class Foo {
private:
// stuff here
private:
void methodForClassBar();
friend FooInterfaceToClassBar;
};
class FooInterfaceToClassBar {
private:
static void inline callMethod(Foo &foo) {
foo.methodForClassBar();
}
friend class Bar;
};
void Bar::someMethod(Foo &foo) {
FooInterfaceToClassBar::callMethod(foo);
}
Is there a other/better (more convenient) method to achieve this, without any runtime performance cost (I'd like to avoid adding interfaces with virtual methods)?
You can restrict the access to the interface's method to only Bar in this way:
class FooInterfaceToClassBar {
private:
FooInterfaceToClassBar() = delete; // avoid accidental instantiation
static void inline callMethod(Foo &foo) {
foo.methodForClassBar();
}
friend class Bar;
};
Although a little inconvenient, this approach gives the most precise control on the visibility, with the minimum of overhead. A variant could be to make the interface class a nested class of Foo. But the only advantage is not to clutter the namespace.
Other approaches
Another approach could be to use inheritance. However, single inheritance will not really do the trick : it can easily give more access to Bar's privacy than expected.
If methodForClassBar() doesn't need itself to access other private stuff, you could isolate it for the Bar access using multiple inheritance. This approach requires however heavy contraints and is not as flexible as yours:
class Foo0 {
//... // the real private stuff goes here
};
class Foo1 {
private:
void methodForClassBar();
friend Bar;
};
class Foo : public Foo0, public Foo1 {
//...
};
...
void Bar::someMethod(Foo &foo) {
foo.methodForClassBar();
}
Furthermore, if you can isolate the method so easily from the rest, you could as well do the same things directly within the Bar method, which makes this alternative look a little bit clumsy.

Access protected function from derived class

I have the following typical scenario, in which I want to hide implementation details in a child class, and expose it through an interface:
template <typename Derived>
class Interface
{
public:
void a()
{
static_cast<Derived*>(this)->_a();
}
};
class Implementation : public Interface<Implementation>
{
protected:
void _a()
{
/*
...
*/
}
};
I think I understand why this doesn't work, and I know that declaring the class Interface as friend of Implementation solves it, but when it comes to more complex hierarchies, like multiple interfaces, and various levels of inheritance(as is my real case), things get really messy.
I would like to avoid having to declare friend class Interface<Implementation> in each class that implements an interface.
Is there an alternative nice-and-clean solution for this problem?
Thanks!
How about using virtual functions and polymorphism?
Create an object in your child class and reassign it to an interface class pointer or reference. Then create a pure virtual function in your interface class and define it in your child class.

Calling a protected method for a member object in C++

If i have two classes, for example like this
class A {
...
protected:
B* test;
aFunction();
};
class B {
...
protected:
A* test1;
public:
bFunction();
};
can I do this inside bFunction() of class B:
bFunction(){
test1->aFunction();
}
Basically, can I call a protected function of a certain class from the class that's not derived from that function?
The "point" of the protected is that only classes that are derived from the baseclass can call those functions.
If you have a good reason to do this, then make the class a friend, e.g. add friend class B; inside class A.
It is recommended to avoid such inevident mutual dependencies. A necessity to use friend functions often indicates bad architecture.
From cplusplus.com:
Private and protected members of a class cannot be accessed from
outside the same class in which they are declared. However, this rules
does not affect friends.
You can call protected and privat methods from other classes, when those are 'friends':
In your case that would be:
Class A {
...
protected:
B* test;
aFunction();
friend class B;
}
Often that is considered bad practice, but for tightly coupled classes that is ok.

How to provide protection to friend function in C++

I have just started learning friend functions in C++.This is the program which I am using for the concept exploration.
#include<iostream>
using namespace std;
class one
{
private:
int age;
public:
one()
{
age=1;
}
void setData(int num)
{
age=num;
}
friend int returnOne(one a);
};
int returnOne(one a)
{
return a.age;
}
class two
{
private:
int roll;
public:
two()
{
roll=0;
}
void setData(int num)
{
roll=num;
}
friend int returnTwo(two b);
};
int returnTwo(two b)
{
return b.roll;
}
int main()
{
one a;
two b;
a.setData(10);
b.setData(12);
cout<<returnOne(a)<<endl<<returnTwo(b)<<endl;
}
Now I am worried that the security of class one and two has been compromised as now anyone can use those globally defined friend functions to access class one's and class two's private members.
How can I provide protection to these friend functions or restrict their usage?
friend ship is mutual. Unless one declares the function as friend in the class definition a function cannot be friended, so it's a choice. If you make it you have to live with it. It makes no sense to make a function friend and then try to prevent it from accessing the class internals because that is exactly the purpose of keyword friend.
Do not misuse or misinterpret friendship.
friendship is used to indicate a intentional strong coupling between two entities. If there exists a special relationship between two entities such that one needs access to others private or protected members but You do not want everyone to have access by using the public access specifier then you should use friendship.
Declaring a friend function in a class extends the classes public interface. You are basically extending the class with more functions (at the cost of tightly coupling those functions).
So you can not stop people using those functions just like you can not stop people using public member methods on your class (they are all part of the public interface).
But you could re-design your friend functions so they do not expose implementation details.
Why not define operator<< for your class instead of a functions that access particular members (this is assuming you are providing these functions simply for streaming (if not then the point is mute)).
std::ostream& operator<<(std::ostream& s,two const& b)
{
return s << b.roll;
}

Becoming a friend through Inheritance C++

Lets say I have two classes
Widget
^
|
Window
and I have another class Application:
Defined as follows
class Application
{
public:
...
private:
friend Widget;
};
This will not give Window access to Applications protected and private members. Is there a way to accomplish this without declaring Window and any subsequent "Widget" as a friend of Application?
No it is not possible.
friendship is not inheritable.
Also, friendship indicates a intentional strong coupling between two entities So if your design indeed demands such a strong coupling go ahead and make them friends. friendship breaking encapsulation is a far too misunderstood concept.
Would defining some methods in the base class to forward calls to Application do the job?
Eg.
class Application
{
public:
...
private:
friend Widget;
void PrivateMethod1();
};
class Widget
{
protected:
void ApplicationPrivateMethod1() { /* forward call to application.PrivateMethod1(); */ }
};
class Window : Widget
{
void SomeMethod()
{
// Access a friend method through the forwarding method in the base Widget class
ApplicationPrivateMethod1();
}
};
If the inherited methods are the only ones that need access to app class than you can declare the individual methods as friends and as long as the window class doesn't override them they can use those methods with friend access.