6

I ran into a code that looks like this:

class Person { ... };

class PersonBuilder{
  Person p;
protected:
  Person& person;
  ...
  operator Person(){
    return std::move(person);
  }
};

What does "operator Person()" trying to do? I see that it returns person, but if that was the whole intent, wouldn't the return type be "Person&" instead of operator? Why do we use "operator" here?

Beg your pardon for a naive question, if it is.

user7865286
  • 344
  • 2
  • 11
  • 9
    http://en.cppreference.com/w/cpp/language/cast_operator – Igor Tandetnik Jun 26 '17 at 03:25
  • @IgorTandetnik Much appreicated – user7865286 Jun 26 '17 at 03:28
  • Please be aware that it is not a good practice to modify an object just by casting. In your code snippet, you move the `person` member, so its content may be invalidated. This means that a second cast directly after that may return a different person. – pschill Jun 26 '17 at 07:25
  • @pschill the simple fix would be to `&&` qualify the conversion, but I think it's intentional – Caleth Jun 11 '21 at 09:47

1 Answers1

0

This syntax defines a Person constructor operator for the PersonBuilder class, so when calling the operator one a PersonBuilder like this:

personBuilder builder;
Person person{builder};

The Person object inside the PersonBuilder class is moved out of it, which is equivalent to casting.

Please note that moving the Person object out of the PersonBuilder object, makes it inaccessible again. You'd be better of returning a copy of the object.