How to Use Deleted Functions to Prevent Object Copying in C++?
Last Updated :
12 Feb, 2024
In C++, the class always has a copy constructor and assignment operator, whether it is default or user-defined which allows the program to create copies of the objects of that class. But sometimes, we need to create a class whose object should not be copied. In this article, we will learn how to use the deleted function concept to prevent object copying in C++.
Prevent Object Copying using Deleted Functions
We can prevent the copying of an object belonging to a particular class by deleting the constructor and copy assignment operator using the delete keyword. To delete a function, we can use the following syntax:
function_declaration {} = delete;
C++ Program to Prevent Object Copying Using Deleted Functions
C++
#include <iostream>
using namespace std;
class NonCopyables {
public :
NonCopyables() = default ;
NonCopyables( const NonCopyables&) = delete ;
NonCopyables& operator=( const NonCopyables&) = delete ;
void showMessage() const
{
cout << "This object cannot be copied." << endl;
}
};
int main()
{
NonCopyables obj1;
NonCopyables obj2 = obj1;
return 0;
}
|
Output
main.cpp: In function ‘int main()’:
main.cpp:26:25: error: use of deleted function ‘NonCopyables::NonCopyables(const NonCopyables&)’
26 | NonCopyables obj2 = obj1;
| ^~~~
main.cpp:10:5: note: declared here
10 | NonCopyables(const NonCopyables&) = delete;
| ^~~~~~~~~~~~
Explanation
We define a class NonCopyables with the default constructor and delete the copy constructor and assignment operator using the delete keyword. In the main() function, we attempt to create a copy of obj1 which results in a compilation error due to a deleted copy constructor. Then we tried to create a copy of the obj1 but we got the error instead.
Share your thoughts in the comments
Please Login to comment...