Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing compilers from defining copy constructors and operator = overload for C++ Classes

Tags:

c++

class

Is there a way by which we can prevent compilers from defining copy constructors, operator = overload for C++ classes.

like image 268
ckv Avatar asked Jun 21 '10 07:06

ckv


People also ask

Can copy constructors be overloaded?

Constructors can be overloaded in a similar way as function overloading. Overloaded constructors have the same name (name of the class) but the different number of arguments. Depending upon the number and type of arguments passed, the corresponding constructor is called.

How can you prevent a class from being copied?

In some cases, an instance of a C++ class should not be copied at all. There are three ways to prevent such an object copy: keeping the copy constructor and assignment operator private, using a special non-copyable mixin, or deleting those special member functions.

Is copy constructor automatically created by compiler?

The compiler also creates a copy constructor if we don't write our own copy constructor. Unlike the default constructor, the body of the copy constructor created by the compiler is not empty, it copies all data members of the passed object to the object which is being created.

How do you make a non copyable object?

Solution and Sample CodeEdit class NonCopyable { public: NonCopyable (const NonCopyable &) = delete; NonCopyable & operator = (const NonCopyable &) = delete; protected: NonCopyable () = default; ~NonCopyable () = default; /// Protected non-virtual destructor }; class CantCopy : private NonCopyable {};


1 Answers

You can declare these functions as private which prevents people from using them when working with your class and at the same time prevents the compiler from generating them.

like image 90
PeterK Avatar answered Oct 11 '22 14:10

PeterK