Search code examples
c++constructorcopy-constructorprivate-constructor

Which is the difference between declaring a constructor private and =delete?


For example, I want to declare a class but I want the client to not be able to use the copy constructor (or copy assignment operator)

Both of the following two does not allow the use of the copy constructor:

1.

class Track
{
public:
  Track(){};
  ~Track(){};
private:
  Track(const Track&){};
};

2.

class Track
{
public:
  Track(){};
  ~Track(){};
  Track(const Track&)=delete;
};

Is one of these ways "more correct" than the other or are equal? Is there any side-effect?

//Does not compile with both the above ways
int main()
{
  Track l;
  Track p(l);
}

Solution

  • Making it private is the "old" way of doing it. The constructor still exists, but it is private, and can only be invoked from within another class member function.

    = delete deletes the constructor. It is not generated by the compiler, and it simply will not exist.

    So most likely, = delete is what you want. (although with the caveat that not all compilers support this syntax yet, so if portability is a concern...)