c++ - Is there a way to make all derived classes friends of one another? -


and if so, in situation might useful?

or (and imagine case), why absolutely useless? (what other approach covers abilities afforded such friendship, in safer , less-leaky way?)

i in situation thought needed such thing. went after entirely different design in end, making class members static. i'm still curious though.

is there way make derived classes friends of 1 another?

the language not provide mechanism specify in base class. you'll have provide friend declarations in every class inherit base class.

i not able suggest more positive since don't know problem trying solve.

in comment, said:

in case, needed access sibling methods, if b , c derive a, needed call b::foo() c::foo(). in case these classes encapsulate different algorithms (so strategy pattern comes mind...) 1 algorithm use substantial portion of algorithm. yet, didn't seem correct derive c b, because c doesn't have "is-a" relationship b.

if c doesn't have "is-a" relationship b, yet c::foo() somehow needs call b::foo(), indicates me b::foo() can use data common both b , c. in case, should possible factor out code non-member function , use b::foo() , c::foo().

change dependency from:

b::foo()    ^    | c::foo() 

to

 <some namespace>::foo()           ^           |   +-------+---------+   |                 | b::foo()          c::foo() 

Comments