C++ Rule Of Three.


The rule of three is one of the rules of C++ under rules of thumb for building an exception safe code. These rules prescribe how default members of the class should be used for exception free practice.

The rule of three is also known as the Law of Big Three or The Big Three and prescribes for class that, if a class defines any of the mentioned three then it should probably explicitly define all three −

  • destructor
  • copy constructor
  • copy assignment constructor

These three are special member functions of class. If none of them is explicitly defined by the programmer, then the compiler provides implicit versions. If any one of the above is explicitly defined that means implicit versions for the other two must be improper and must be redefined.

This happens because implicitly generated constructors and assignment operators’ shallow copy the data members. We require deep copy when class contains pointers pointing to dynamically allocated resources.

The default destructors remove the unused objects. When there is no copy constructor defined then the destructor will run twice, once for objects that contain the copy and second for objects from which the data members are copied. To avoid this, explicit definition becomes necessary.

Let us understand with an example where there is no copy constructor and no copy assignment operator, but destructor is present −

Example

 Live Demo

#include <stdio.h>
class Numbers{
private:
   int num;
   int* ptr;
   public:
   Numbers( int n, int* p ) //copy constructor{
      num =n ;
      ptr = new int[ num ];
   }
   ~Numbers() //destructor{
      delete ptr;
      ptr = NULL;
   }
};
int main(){
   int arr[ 4 ] = { 11, 22, 33, 44 };
   Numbers Num1( 4, arr );
   // this creates problem
   Numbers Num2( Num1 );
   return 0;
}

Output

*** Error in `./a.out': double free or corruption (fasttop): 0x0000000001f46c20 ***
Aborted
  • This happened because the destructor is called twice when the program goes out of scope. First deletion of Num1 and then for Num2. Default copy constructor creates a copy of pointer ptr but not allocated memory for it. So, when Num1 is removed subsequent ptrs cause the program to crash.

Updated on: 28-Jul-2020

517 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements