Javatpoint Logo
Javatpoint Logo

The Rule of Five in C++

In this article, you will learn about the Rules of Five in C++ with their syntax and examples.

The Rule of Five states that if your class needs any of the following, it probably needs all of them:

  • Destructor: It is used to avoid resource leaks when an object goes out of scope.
  • Copy Constructor: It is used to properly copy class resources when an object is copied.
  • Copy assignment operator: It is used to copy resources when one object is assigned to another.
  • Move Constructor: It is used to efficiently move resources, rather than copy when an object is moved.
  • Move assignment operator: It is used to move resources when one object is moved into another.

In essence, the rule says that if your class manages resources like pointers or file handles, you need to properly implement the constructors, destructor, and assignment operators to avoid issues with cleaning up those resources. Following the rule prevents resource leaks, invalid object states, and unnecessary copying.

The importance of C++'s Rule of Five

The Rule of Five exists in C++ due to the need to properly manage resources like pointers, file handles, and dynamic memory allocations. Here are some key reasons why following the Rule of Five is important:

  1. Prevent resource leaks: The destructor allows objects to free/close resources when they go out of scope. Without a destructor, resources may be leaked.
  2. Avoid invalid states after copying: The copy constructor and assignment operators properly copy resource ownership from one object to another. Without them, copies of an object could end up with broken/invalid pointers.
  3. Improve efficiency through move semantics: Move constructors and move assignment operators transfer resources instead of copying them, which is faster.
  4. Consistency: If a class needs one special method, like a destructor or copy constructor, it likely needs the rest to work correctly. The rule sets consistent expectations.
  5. Encapsulation: The rule encapsulates resource handling neatly inside the class, preventing issues from incorrectly using/copying objects.

It establishes clear best practices for classes that manage resources, leading to correct program behaviour, and avoiding difficult bugs. Following the five standard methods ensures proper resource handling when initializing, destroying, copying, or moving objects.

1. Destructor:

A destructor is a unique function invoked automatically upon an object's destruction or out-of-scope. Its main purpose is to free up resources that the object may have acquired during its lifetime.

Syntax:

It has the following syntax:

Here,

  • Destructors have the same name as the class, prefixed with a tilde (~).
  • Destructors take no arguments and have no return type.

Example:

Let us take an example to illustrate the destructor in C++.

In this example, the destructor closes the file handle that was opened by the class to prevent resource leaks when the object gets destroyed. Resource handling is neatly encapsulated inside the class via the destructor.

2. Copy Constructor:

A copy constructor is a unique type of Constructor that uses an already-existing object of the same class to initialize an object. It is used to initialize new objects from existing ones.

Syntax:

It has the following syntax:

  • It is a constructor that takes a reference to an object of the same class as a parameter.
  • It has a single parameter that references the same class type.
  • The parameter must be passed by reference and not by value.
  • It is generally used to deep copy objects during initialization.

Example:

Let us take an example to illustrate the copy constructor in C++.

In this example, the copy constructor initializes p2 as a copy of p1 by copying its name and age data members. It prevents shallow copying of objects.

3. Copy Assignment Operator:

The copy assignment operator assigns values of one object to another existing object of the same class. It assigns one object to another object of the same class.

Syntax:

It has the following syntax:

  • It overloads the = operator.
  • It has a parameter that refers to an object of the same class.
  • The parameter must be passed by reference.
  • It assigns the data members of the passed object to the current object.
  • It returns a reference to the current object (*this).

Example:

Let us take an example to illustrate the copy assignment operator in C++.

In this example, the copy assignment operator is overloaded to assign c1's values to the existing c2 object. It copies member data and returns the current updated object.

4. Move Constructor:

A move constructor transfers resource ownership from one object to another instead of making a copy. It is used to implement move semantics, which transfers resources faster than copying.

Syntax:

It has the following syntax:

Example:

Let us take an example to illustrate the move constructor in C++.

Here, the move constructor efficiently transfers the data pointer from v1 to v2. v1 is left in a valid null state after the move. Therefore, it transfers resources instead of copying them. It enables efficient move semantics.

5. Move Assignment Operator:

The move assignment operator transfers the resources from one object to another instead of copying. It is used to implement move semantics, which transfers resources faster than copying.

Syntax:

It has the following syntax:

  • It overloads the = operator, similar to copy assignment.
  • It takes an rvalue reference (&&) to the same class type.
  • Resources and data members are transferred from the old_obj object to the current object.
  • The old_obj is left in a valid but unspecified state.
  • It returns a reference to the current object (*this).

Example:

Let us take an example to illustrate the move assignment operator in C++.

Here, the move assignment operator efficiently transfers the data pointer from s1 to s2 instead of creating a new copy. The s1 is left in a valid empty state after the move. Therefore, it transfers resources instead of copying them, enabling move semantics.

Example:

Let us take a C++ program that demonstrates the use of all five special member functions: Destructor, Copy Constructor, Copy Assignment Operator, Move Constructor, & Move Assignment Operator.

Output:

Constructor - Allocated memory for 5 integers.
Copy Constructor - Copied 5 integers.
Constructor - Allocated memory for 3 integers.
Copy Constructor - Copied 3 integers.
Move Constructor - Moved resources.
Constructor - Allocated memory for 2 integers.
Move Assignment Operator - Moved resources.
Destructor - Deallocated memory.
Destructor - Deallocated memory.
Destructor - Deallocated memory.
Destructor - Deallocated memory.
Destructor - Deallocated memory.






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA