Prev: Best practice for maintaining an internal reference/pointer to another class
Next: omission of "virtual" in overridden method declarations in derived classes
From: Ulrich Eckhardt on 25 Feb 2010 19:50 Sal wrote: > Imagine you have two classes, ClassA, and ClassB. ClassA is just some > class that changes its internal state from time to time, and ClassB is a > class that provides additional content, based on the current state of a > ClassA instance [...] > > class ClassA; > > class ClassB > { > ClassA *myItem; > public: > ClassB(const ClassA &item) > : myItem(&item) { } > } > > I'm sure you see the problem with this immediately; although the intention > is for the user to "new" a ClassA and pass it into the constructor to > ClassB (that way the internal pointer of ClassB won't change), the > constructor takes in a reference. Which means theoretically the user could > create a ClassA on the stack, pass it to a ClassB, then have it deleted > and now the ClassB points to garbage. Alternatively, it could be written > as: > > class ClassB > { > ClassA *myItem; > public: > ClassB(const ClassA *item) > : myItem(item) { } > } > > But, I'm under the impression that passing pointers around probably isn't > the best practice (in general). What you need is a kind of handle that makes sure that the ClassA instance remains alive as long as the ClassB instance referencing it remains alive. Alternatively, it could null the reference in the ClassB instance to signal that the referenced object ceased to exist. Typical approaches would use smart pointer classes like e.g. boost::shared_ptr and boost::weak_ptr. An alternative would be a stronger form of association, i.e. aggregating the two with each other. Maybe your decision to keep them separate was the first step in the wrong direction? > So, I guess my question is which one makes more sense from an outside > user's standpoint (or does neither make sense)? You could also pass the ClassA instance to every call that uses it. Of course, that effectively forbids passing in different ClassAs when the ClassB maintains some state in between. Uli -- Sator Laser GmbH Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932 [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ] |