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++ program demonstrating a class that cannot be copied #include <iostream> using namespace std;
class NonCopyables {
public :
NonCopyables() = default ;
// Delete copy constructor
NonCopyables( const NonCopyables&) = delete ;
// Delete assignment operator
NonCopyables& operator=( const NonCopyables&) = delete ;
// Member function to display a message
void showMessage() const
{
cout << "This object cannot be copied." << endl;
}
}; int main()
{ // Create an instance of the NonCopyables class
NonCopyables obj1;
// Call the showMessage method to display a message
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.