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.

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:

//noncopyalbe sample

class NonCopyable
{
protected:
    NonCopyable() {}
    ~NonCopyable() {}
private:  //  make class non-copyable by making copy-constructor and assignment operator private.
    NonCopyable(const NonCopyable&);
    NonCopyable& operator=(const NonCopyable&);
};

class ExistingClass : private NonCopyable
{
public:
    ExistingClass() {cout <<"Existing class";} // default constructor available
};

int main()
{
	ExistingClass obj1, obj2;	
	// call Assignment
	obj1= obj2;	//Error	1	error C2248: 'NonCopyable::operator =' : cannot access private member declared in class 'NonCopyable'	e:\data\c++_samples\cpp_explicit\main_explicit.cpp	31	

	//call Copy constructor
	ExistingClass obj_copy_ctor = obj1;//Error	2	error C2248: 'NonCopyable::NonCopyable' : cannot access private member declared in class 'NonCopyable'	e:\data\c++_samples\cpp_explicit\main_explicit.cpp	31	


	return 0;
}


Leave a Comment