Jahid
Jahid

Reputation: 22428

How to prevent object=constructor(); assignment in c++

This is what I am trying to do:

class A{
    public:
    A(){/*need to initialize something here*/}
};

int main(){
    A a;      //OK
    a=A();    //not OK
    a=A(b);  //not OK
    ///Only A a; needs to be allowed.
    return 0;
}

I need to initialize something while preventing object initialization with copy constructor and also prevent assignment to existing object.

Note: It would be good if I can do this without >=C++11.

Upvotes: 0

Views: 385

Answers (4)

Dietmar Kühl
Dietmar Kühl

Reputation: 153840

You can just = delete; the copy assignment operator:

class A {
    // ...
    void operator=(A) = delete;
};

Alternatively, if you don't use C++11 you can make the copy assignment private.

Upvotes: 3

Fatih BAKIR
Fatih BAKIR

Reputation: 4715

You can achieve your goal by declaring the assignment operator and the copy constructor in the private part, and not defining them.

For example:

class A {
private:
    A(A&); // declared, not defined

    void operator= (A&); // declared, not defined

public:
    A() { //do regular stuff }
}

However, if you are using C++11/C++14, you can use the delete keyword for more explicit case of this:

class A {
public:
    A() { //do regular stuff }
    A(A&) = delete;

    void operator= (A&) = delete;
}

Since the move constructor and the move assignment operators will not be generated if you declare any of the destructor / copy constructor / assignment operator, you don't need to the same thing for them.

Upvotes: 4

Vlad from Moscow
Vlad from Moscow

Reputation: 310990

You can define the assignment operator as deleted. For example

class A{
    public:
    A(){/*need to initialize something here*/}
    A & operator =( const A & ) = delete;
};

Or you can declare it private.

class A{
    public:
    A(){/*need to initialize something here*/}
    private:
    A & operator =( const A & );
};

Upvotes: 1

Jarod42
Jarod42

Reputation: 217293

Since C++11, just delete assignment operator:

class A{
    public:
    A(){/*need to initialize something here*/}
    A& operator =(const A&) = delete;
};

Upvotes: 8

Related Questions