We have 50 classes and out of these we want to make 10 classes noncopyable, means, we cannot copy or assign objects of same class type. How would you achieve this? Note that we cannot change the body of classes.

(Last Updated On: January 1, 2015)

Answer:

One of the solutions is, create a separate base class, say “NonCopyable” and make copy constructor and assignment operator declaration private leaving constructor and destructor public or having default constructor.

When we create object of existing class it will first call the constructor of base(NonCopyalbe) class then existing class. Same will happen for copy constructor and assignment operator.

Since constructor of NonCopyable class is public it is ok to call base class constructor then derived class constructor. But, as copy constructor and assignment operator in NonCopyable class is private, it will flash an error when we call copy constructor or assignment operator of Existing class.

Example: