Implementing Associations

By Frank Hellwig

Dr. Dobb's Journal June 1998

(a)
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)
Person* bill = new Person();
Dog* fido = new Dog();
bill->addPet(fido);
fido->setMaster(bill);
(c)
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().

Back to Article


Copyright © 1998, Dr. Dobb's Journal