2
#include <iostream>

class A{
};

class B: public A{
public:
    B(A&& inA){
        std::cout<<"constructor"<<std::endl;
    }
};

int main(){
    B whatever{A{}};
    whatever=A{};
}

This outputs

constructor
constructor

at least with C++14 standard and GCC. How is it defined that assignment operator can result in call to constructor instead of operator=? Is there a name for this property of assignment operator?

Euri Pinhollow
  • 332
  • 2
  • 17

1 Answers1

3

Since you meet all the conditions for generating a move-assignment operator. The move-assignment operator the compiler synthesizes for you is in the form of:

B& operator=(B&&) = default;

Recall that temporaries can be bound to const lvalue references and rvalue references. By Implicit Conversion Sequences, your temporary A{} is converted to a temporary B which is used to make the move assignment. You may disable this with explicit constructors.

WhiZTiM
  • 21,207
  • 4
  • 43
  • 68
  • "your temporary A{} is converted to a temporary B" - can you cite the draft? I am only able to find mention of derived-to-base conversion in the page you linked. – Euri Pinhollow Oct 09 '17 at 18:21
  • @EuriPinhollow, this has nothing to do with "derived-to-base (`B->A`)" conversion, and there is no such context in OP's snippet.... OP's code has a [*Converting Constructor*](http://eel.is/c++draft/class.conv#ctor-1)[class.conv.ctor] that takes an rvalue to an object of `A`, namely: `B(A&&)`. This means any `rvalue` object of `A` can be converted to `B`. [User-defined Conversion Sequences](http://eel.is/c++draft/over.best.ics#over.ics.user)[over.ics.user] takes into account all possible methods of implicit conversion from "the Type you passed as argument" to "the Type expected" – WhiZTiM Oct 09 '17 at 19:35
  • Edit this into answer please and I am accepting it. This part is the most important one. – Euri Pinhollow Oct 09 '17 at 19:47