4

What is the difference between explicitly declaring classes special functions default.

class Myclass
{
public:

    Myclass() = default;
    virtual ~Myclass() = default;

    Myclass(MyClass&&) = default;
    Myclass& operator=(MyClass&&) = default;

    Myclass(const MyClass&) = default;
    Myclass& operator=(const MyClass&) = default;
};

MyClass{};

What is the difference between this 2 declarations? Why explicitly specify the default behavioral functions as default??

Eduard Rostomyan
  • 7,050
  • 2
  • 37
  • 76
  • the `class MyClass{};` version does not have a virtual destructor. – sp2danny Jun 14 '17 at 14:29
  • `What is the difference between this 2 declarations?` What 2 declarations? You seem to only have included 1 declaration of each special member function. – underscore_d Jun 14 '17 at 14:35
  • 3 reasons: making it explicit to the reader, forcing the compiler to generate them in corner cases where it does not actually generate defaults, making a default private (so that a friend class has access to the default one) – arkan Aug 22 '23 at 04:34

1 Answers1

9

Because under certain conditions the compiler might not add the constructors, destructor or operators even though you may want the compiler-generated defaults. Then by using the explicit default designator the compiler will do that anyway.

You can find out more in e.g. this class reference.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 4
    also sometimes being explicit can add clarity, you signal that the default generated one was by choice rather than mistake. – John Smith Jun 14 '17 at 12:17