I have a set of classes
class myClassA{
friend class MyFatherClass;
};
class MyFatherClass{
...
};
class MySonClass : public MyFatherClass {
};
My father class can access all the methods of the class MyClassA.
I would like as well that all the class which will extend MyFatherClass will be able to call such methods.
I can see just 2 options:
- at any time I go to add in myClassA the new class as a friend. ( I do not like it )
- I create some protected wrapper in the father function to access the method from the class myClassA. (slightly better but i still do not like it as well because i have to create a new wrapper at any time a new method is created in myClassA)
Do you have any idea for a more elegant solution to the problem?
Thanks
First off… what does elegant mean? Less code for you to write? I suggest you don’t compromise when it comes to readability.
Using friendship should not be a decision taken lightly. There are numerous threads on SO dealing with this, but here I’ll just assume you already know what this implies.
Option 1) is a lot more readable. When someone sees the class, they will directly know who has access to it. Code should be expressive, and this option describes the intent perfectly.
Option 2) is a bit of an overkill. You’re writing a wrapper just so you can access some functions… why not make them
publicto start with, since the wrapper has public access. It’s just an added layer of abstraction for nothing.You should first think about functionality (both work), expressiveness and readability (option 1 is definitely better here).