In older versions of C++ if one wanted to prevent copying
of a class object they would typically declare the Copy Constructor
and operator=()
in the private section of a class as such:
class Foo {
public:
Foo(){} // Default
~Foo(){} // Default
private:
Foo( const Foo& c ); // not implemented
Foo& operator=( const Foo& c ); // not implemented
};
Which is pretty straight forward. Now with newer versions of C++ we can now do this instead.
class Foo {
public:
Foo() = default;
~Foo() = default;
private:
Foo( const Foo& c ) = delete;
Foo& operator=( const Foo& c ) = delete;
};
My question then becomes this: With the modern approach of declaring these as deleted
functions, does it matter or make any difference if they are defined in the public, protected or private sections of its class?
For example is there any difference between the one above and this:
class Foo {
public:
Foo() = default;
~Foo() = default;
Foo( const Foo& c ) = delete;
Foo& operator=( const Foo& c ) = delete;
};
Edit:
I have accepted ShadowRanger's answer due to their explanation with examples as well as providing a link to this Q/A that clearly explains the recommendations and why...
It has come to my attention that in the first example when they are declared private
you will get additional compiler errors
on top of the already existing compiler errors
that are already being generated when they are being declared as public
.