Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: Advanced
Jun 26, 1998



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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;
  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 likes
using namespace std;
void main() 
char *s; //only a pointer, not a buffer. programmer's mistake
strcpy( s, "hello world"); //disastrous!  strcpy holds rather than owns a buffer
Danny Kalev
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date