Galaxian Galaxian - 4 years ago 89
C++ Question

Objects that can be initialized but not assigned

I need to create a class whose objects can be initialized but not assigned.

I thought maybe I could do this by not defining the assignment operator, but the compiler uses the constructor to do the assignment.

I need it to be this way:

Object a=1; // OK
a=1; // Error


How can I do it?

Answer Source

You can delete the assignment operator:

#include <iostream>
using namespace std;

struct Object
{
    Object(int) {}
    Object& operator=(int) = delete;
};

int main()
{
    Object a=1;    // OK
    a=1;           // Error
}

Alternative Solution

You can use the explicit keyword:

#include <iostream>
using namespace std;

struct Object
{
    explicit Object(int) {}
};

int main()
{
    Object a(1);    // OK - Uses explicit constructor
    a=1;           // Error
}

Update

As mentioned by user2079303 in the comments:

It might be worth mentioning that the alternative solution does not prevent regular copy/move assignment like a=Object(1)

This can be avoided by using: Object& operator=(const Object&) = delete;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download