To have or to hold?

Ownership in its OO sense relates to the responsibility for the creation and the destruction of an object. An object (in its broader sense) is an owner of some other resource if and only if it has the responsibility for both its construction and destruction. In that respect, an object which contains some other object also owns it since its constructor and destructor are responsible for the invocation of the embedded object’s constructor and destructor, respectively. This is the well-known hasa relation. A similar relation is holdsa. It is distinguished from hasa by one factor: ownership. In other words, a class containing indirectly (by means of a reference or a pointer) another object, which is constructed and destroyed independently, holds that object. For example:

 class Phone {/*...*/}; class Dialer {/*...*/};class Modem {	  Phone* pline;   Dialer& dialer;  public:  Modem (Phone *pp, Dialer& d) : pline(pp), dialer(d) {} //Phone and Dialer objects are constructed and destroyed independent of Modem};void f() {Phone phone; Dialer dialer;Modem modem(&phone, dialer); //...use modem}//phone and dialer objects automatically destroyed here

Mind that modem is allowed to invoke any member function of phone and dialer as long as it doesn’t destroy any of them.When designing real-world software, it’s highly important to state the ownership relations among objects clearly. Many bugs and design errors are a result of confusing hasa with holdsa:

 #include  // declaration of:  void strcpy(char * to, const char *from); and the likesusing namespace std;void main() {char *s; //only a pointer, not a buffer. programmer's mistakestrcpy( s, "hello world"); //disastrous!  strcpy holds rather than owns a buffer}
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: