Gert Van den Eynde said:
Hi all,
I have a question on interface design: I have a set of objects that are
interlinked in the real world: object of class A needs for example for the
operator() an object of class B. On what arguments do you decide whether to
pass a reference to the object of class B to the member function like this
operator()(classB& objB) or to have in class A a data member (a const
pointer to a class B object or so) and have this set during construction or
with a Set-function? Class B is designed to deliver the necessary data
through Get-functions. Or do friends come in handy here?
Thanks for tips,
gert
Hi,
These are good questions with no "right" answers, though many will try to
tell you what is "right". The question here is, "who is managing the
B-object"? If you want to hide what is happening to B, then it might be a
good idea to encapsulate the object inside of A (by composition, I mean).
If you have another set of code which is managing both an A and a B, then it
probably does not make much sense (to place a B object inside of A).
Overriding, that last suggestion, however, is that if the B-object is
needed in the implementation of A, then you probably do want it in your
A-class design (or use inheritance, possibly - not likely here).
Again, it's kind of silly...what I wrote. I can think of so many
scenarios where this rule of thumb would be... silly.
If you are fairly new to C++ or this type of design decision making
process, then I recommend that you try as many ways as you can think of.
Look at the tradeoffs of using each technique. Rules of thumb break easily
in C++ world, though many do exist. Try to get some experience with these
decisions and get a feel for what you like most.
Some (sometimes) competing ideas:
Friends
Inheritance (private, protected, public)
Composition (a B inside of an A) by value
Composition by reference
etc.
People will tell you inherit in a "IS-A" relationship and compose in a
"HAS-A" relationship. I don't stick hard and fast to this notion. Many
times, I strive hard to keep away from inheritance and virtual functions.
Not always - sometimes it is the best solution for me - it's just that
things better be really ripe for inheritance before I'll use it.
Anyway, look up H. Sutter's words of wisdom on inheritance and composition
(Exceptional C++ and More Exceptioinal C++). Lippman's book has some good
stuff too (C++ Primer). And, of course, B. Stroustrop will undoubtedly have
some great guidelines for you (The C++ Programming Language).
Shane