![]() |
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 FunctionsWe 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 FunctionsC++
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. |
Reffered: https://www.geeksforgeeks.org
C++ |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |