Search code examples
c++copy-assignment

synthesized default constructor as deleted


I read this in the book:

The synthesized copy-assignment operator is defined as deleted if a member has a deleted or inaccessible copy-assignment operator, or if the class has a const or reference member.

And why we can not use reference type?


Solution

  • you're talking about default constructor (and not reassignment or copy constructor).

    const member whose type does not explicitly define a default constructor

    It forbids the default constructor, else you will have an uninitialized const value (so useless). (if it was not const, the fact that it was uninitialized is not a problem, we may assign it later).

    a reference member that does not have an in-class initializer

    It is forbidden also, as reference is similar to a non null const pointer.

    struct NoDefaultConstructor
    {
        // No default constructor can be generated.
    
        const int i; // which value to set by default ?
        int& r; // reference which object by default?
    };
    
    struct InClassInitializerSoDefaultConstruct
    {
        // default constructor is generated here.
        const int i = 42;
        int j;
        int& r = j;
    };
    

    Edit to answer edited Q

    For assignment, const value cannot be changed. and reference are like non null const pointer.

    Note that copy constructor doesn't have this restriction because you may (and have to) initialize const` value.