Handle-Body Example
Example 59 demonstrates the scenario given in Defining Handle Classes that Automatically Create Bodies. For the complete source code, see buildspace\examples\pointer\HandleBodyEx1.cpp. (For comparison, the same example is also implemented according to the second guideline in HandleBodyEx2.cpp.)
The UML diagram in Figure 38 illustrates the model.
Figure 38 – Bicycle example implementation
Example 59 – Implementing a derived handle class that automatically creates a body
First implement BicycleImp, the bicycle body class.
 
class BicycleImp : public RWBodyBase {
public:
friend class Bicycle; //1
void showInformation(void) const;
private:
BicycleImp(void) {;} //2
BicycleImp(const RWCString& model, const RWDateTime& buildDate,
const RWCString& manufacturer) ;
RWCString model_;
RWDateTime buildDate_;
RWCString manufacturer_;
};
 
//1 The handle class must be a friend, because the body constructors are private.
//2 The constructors are protected, so the only way to build bodies is through the handle.
Now implement the matching handle class, Bicycle, which duplicates the body’s interface.
 
class Bicycle : public RWHandleBase {
public:
Bicycle(void) {;} //1
Bicycle(const RWCString& model, const RWDateTime& buildDate,
const RWCString& manufacturer);
void showInformation(void) const;
protected:
BicycleImp & body(void) const;
};
 
Bicycle::Bicycle(const RWCString& model, const RWDateTime& buildDate, const RWCString& manufacturer) : RWHandleBase(new
BicycleImp(model, buildDate, manufacturer)) {;} //2
 
BicycleImp & Bicycle::body(void) const {
return (BicycleImp &) RWHandleBase::body(); } //3
 
void Bicycle::showInformation(void) const {
body().showInformation(); } //4
 
//1 This default constructor does not instantiate a body on the heap. Any function applied to an instance created by this constructor throws an RWTHRInvalidPointer exception.
//2 This constructor initializes a body on the heap, which is the correct way to build bodies.
//3 The body() function is overridden to return a BicycleImp reference, using a type cast.
//4 The handle implementation of showInformation() forwards the call to the body.