2

I have a piece of code that looks something like this:

class B
{
private:
    const A& obj;
    size_t val;

    // private - prohibited
    B& operator=(const B& other);

public:
    B(const A& obj_): obj(obj_)
    {
        val = 0;
    }
};

class C
{
    void func()
    {
        A a1;
        B b1(a1);
        B b2 = b1; // should throw error?
    }
}

Class B has a private assignment operator. Nonetheless assignment in C::func() compiles without errors. But how?

7
  • 4
    Assignment can only occur to an object that already exists. Here, b2 is a new object so it's being constructed. Commented Jul 24, 2019 at 16:55
  • 3
    @John That's not how it works. Optimizations do not allow the compiler to ignore the language rules. To be used with the move constructor, objects need to be actual temporaries according to the language, not just their usage. Commented Jul 24, 2019 at 16:55
  • 1
    @John No need to guess. It's copy initialization, no assignment operator involved at all. Commented Jul 24, 2019 at 16:56
  • 1
    Regarding title: Deleting an assignment operator is different thing from declaring it private. As such, the title is highly misleading. Commented Jul 24, 2019 at 16:58
  • 1
    B b2 = b1; looks like an assignment but is not, it's only uses a constructor. This can be confusing when first encountered. Commented Jul 24, 2019 at 22:18

2 Answers 2

6

B b2 = b1 does not use the assignment operator, because it's not assignment, it's copy initialization - using constructor, not assignment operator.

See also copy initialization

Sign up to request clarification or add additional context in comments.

Comments

2

That's the copy constructor getting called, not the assignment operator.

The reason being is that when you initialize a variable, a constructor (in this case, the copy constructor) gets called.

B b2 = b1; // construction

This is different from assignment

b2 = b1; // b2 is already declared, so assignment

To stop this behavior, just delete your copy constructor.

1 Comment

Instead of making the copy constructor private, it would be better to delete it if your intention is to make the class non-copy-constructible. It will better show intent in the code and compiler errors.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.