How can you prevent object copy in C++?

(Last Updated On: June 6, 2017)

Answer includes how to prevent object copy in C++ of a class with a simple example using copy constructor and assignment operator with C++ program example.

There is a simple trick that we can apply in C++ class that is by making copy constructor or assignment operator private, we can prevent copy or assignment of an object of a class.

In below class Sample we have make copy constructor and assignment operator overloading private. Point to note that we need to write empty constructor public as we want to allow object of the class to be created.

So, when we create class objects in main() program and try to call copy constructor e.g. Sample sObj3=sObj1 or assignment operator e.g. sObj1=sObj2 etc compiler will throw an error complaining that private members of a class cannot be accessed.

C++ Code Example: