Copying in C++ is handled in two ways
- the copy assignment operator; and
- the copy constructor
Unfortunately, if the class definition does not explicitly declare a copy constructor or a a copy assignment operator, the compiler provides an implicit version which is a public member function.
Now, if we want to make a class noncopyable, we can simply define its copy constructor and copy assignment operator as private members. But, it makes more sense to have a noncopyable base class. If a class derives from the noncopyable base class, it too will be noncopyable, since the copy of an object of a derived class must necessarily invoke the copy constructor or copy assignment operator of the corresponding base class.
namespace Base
{
class cNonCopyable
{
protected:
cNonCopyable(){}
private:
cNonCopyable(const cNonCopyable&);
cNonCopyable operator =(const cNonCopyable&);
}
}
By making the copy constructor or copy assignment operator private, we ensure that the derived class is noncoyable as well. By just providing the declaration and not implementing them, we ensure that the compiler does not provide its own versions and a linking error is generated if they are used anywhere in the program.