Implementing Associations
By Frank Hellwig
Dr. Dobb's Journal June 1998
<B>(a)</B> class Dog; class Person { public: void addPet(Dog* d) { pets_.add(d); } private: Vector pets_; }; class Dog { public: Dog() : master_(0) { } void setMaster(Person* p) { master_ = p; } private: Person* master_; }; <B>(b)</B> Person* bill = new Person(); Dog* fido = new Dog(); bill->addPet(fido); fido->setMaster(bill); <B>(c)</B> Dog::setMaster(Person* p) { master_ = p; master_->addPet(this); }
Example 1: (a) Partial declaration of the Person and Dog classes; (b) creating and associating a dog and its master; (c) calling addPet() from within setMaster().
Copyright © 1998, Dr. Dobb's Journal