Search code examples
c++operators

Is it possible to declare operator= private and have it synthesized by the compiler at the same time in C++


I am happy with the operator =, which is synthesized by the compiler automatically. But I want it to be private and do not want to bloat my code with page long definitions of the type

Foo& Foo::operator= (const Foo& foo)
{
    if (this == &foo)
        return *this;

    member1_    = foo.member1_;
    member2_    = foo.member2_;
    member3_    = foo.member2_;
    ...
    member1000_ = foo.member1000_;

    return *this;
} 

Please, is there a way to do this?


Solution

  • In C++11 it is:

    class Foo
    {
        Foo& operator=(const Foo& source) = default;
    public:
        // ...
    };
    

    Unfortunately, most compilers haven't implemented this part of the new standard yet.