C++ newbie question. Please, verify I’m doing it right.
I have a global application class spawning it’s little kids and I need to give the kids access to some of the application facilities. So I decided to pass them to children by reference.
I tested the idea as show below. It seems to work fine. I just wanted to make sure I’m not doing something dangerous. Might be there any pitfalls I overlooked?
Dad creates children and gives them his car keys:
#include <iostream> using namespace std; class CCarKeys { public: CCarKeys(const string& Name) : _Name(Name) {} string _Name; }; class CChild { public: CChild(CCarKeys& CarKeys) : _Name('Child'), _CarKeys(CarKeys) {} string _Name; CCarKeys& _CarKeys; void TestHasKeys() {cout << 'I got ' << _CarKeys._Name << endl;} }; class CDad { public: CDad() : _Name('Dad'), _HondaCarKeys('Honda keys'), _ChevyCarKeys('Chevy keys') {} string _Name; CCarKeys _HondaCarKeys; CCarKeys _ChevyCarKeys; CChild *_Boy; CChild *_Girl; void MakeBoy() {_Boy= new CChild(_HondaCarKeys);} void MakeGirl() {_Girl= new CChild(_ChevyCarKeys);} }; int main () { CDad Dad; Dad.MakeBoy(); Dad.MakeGirl(); Dad._Boy->TestHasKeys(); Dad._Girl->TestHasKeys(); }
Looks good to me (if keys is all they need). They might need some other services from Dad which are requested later – like:
But they don’t have a reference to Dad, so they won’t be able to do that. So I would have the CChild constructor take a
thisreference, too.etc.
And then
CChildconstructor would need to takeICashProviderandIChaffeur, as wouldCWifeandCGirlfriend(andCBoyfriend, perhaps). At this point, I think you might realize that this level of granularity is pointless in the face ofDad‘s responsibilities and you just give everyonethisand haveDadauthenticate requests by forcing callers to send their ownthison some methods, so you don’t haveDadperforming incest or changing theCWife‘s diaper.