The “Big Three Rule” or the “Big Two Rule”?

The famous “Big Three Rule” says that if a class needs any of the Big Three member functions (copy constructor, assignment operator, and destructor), it needs them all. Generally, this rule refers to classes that allocate memory from the free store. However, many other classes require only that the Big Two (copy constructor and assignment operator) be defined by the user; the destructor, nonetheless, is not always required.

 class Year{ private:   int y;  bool cached; //has this object instance been cached? public:  //...  Year(int y);  Year(const Year& other) //cached should not be copied  {     y = other.getYear();  }     Year& operator =(const Year&other) //cached should not be copied  {     y = other.getYear();     return *this;  }    int getYear() const { return y; }};//note: no destructor is required for class Year

In this example, Class Year does not allocate memory from the free store nor does it acquire any other resources during its construction. A destructor is therefore unnecessary. However, the class needs a user-defined copy constructor and assignment operator to ensure that value of the member ‘cached’ is not copied because it is calculated for every individual object separately.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: