NonCopyable Objects in c++

This entry was posted on
  • Snippet
  • Tutorial
  • Cpp

Sometimes, you want to prevent the compiler from making objects. However, in C++, a copy of an object can be made in a number of situations. The most obvious is a direct assignment. Less obvious, but equally valid, is a function call using pass-by-value.

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 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. This is because the copy of an object of a derived class must necessarily invoke the copy constructor or the copy assignment operator of its base class.

namespace Base
  class cNonCopyable
    virtual ~cNonCopyable(){}


    cNonCopyable(const cNonCopyable&);
    cNonCopyable& operator =(const cNonCopyable&);

By making the copy constructor or copy assignment operator private, we ensure that the derived class is noncopyable 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.