• entries
23
15
• views
30101

# NonCopyable objects

619 views

Sometimes, you don't want to encounter a situation where something made a copy of the object. In C++, a copy of an object can be made in a number of situations. The most obvious is 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 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.

There are no comments to display.

## Create an account

Register a new account