user17597436
user17597436

Reputation:

Am I correct about how this C++ code works?

In this code :

    class iop {
    public:
        iop(int y) {
            printf("OK\n");
        }

        iop() {
            printf("NO\n");
        }
    };

    int main()
    {
  line 1-   iop o;
  line 2-   o = 8;
  line 3-   return 0;
    }

My conclusion of the way this C++ code work with is:

  1. Create an object of iop class (o) using the default parameterless constructor.

  2. Create an rvalue object of iop class using the constructor with parameter (int) and using the overloaded operator (operator = (iop&&)) to assign it to the object (o) then call the destructor of that rvalue.

  3. Call the destructor of the object (o).

Is my conclusion correct?

Edit This code also compiled

class iop {
public:
    iop(int y) {
        printf("OK\n");
    }

    iop() {
        printf("NO\n");
    }
};

int main()
{
    iop o(5);
    o = 8;
    return 0;
}
output :
OK
OK

That is mean two object are created (o) and one is temporary and the operator= assigen (o) with the temporary object that its constractor argument is 8

Upvotes: 2

Views: 234

Answers (1)

bolov
bolov

Reputation: 75668

The class iop has implicitly defined copy and move constructors and assignments.

o = 8;

This will attempt to call operator=. As I've stated the copy and move assignment operators are implicitly defined:

iop& operator=(const iop&);
iop& operator=(iop&&);

Because iop is implicitly constructible from int, both operators are viable, but the move one is preferred as is a perfect match.

So yes, a temporary is created from 8, that is moved into o. At the end of the full expression (at ;) that temporary is destroyed. At the end of main scope o is destroyed.

So your code is more or less equivalent to o = iop{8}.

Sidenote: if you make the int constructor explicit i.e. explicit iop(int y) then o = 8; will no longer compile.

Upvotes: 4

Related Questions