They demanded suddenly in the derived class to overload the reduction operator to the base (this is a lab, I myself would not do this).

#include <iostream> class A { }; class B: public A { operator A() { std::cout << "operator A()\n"; A a; return a; } }; int main() { B b; A a = (A)b; } 

When you start it does not display anything - that is, it does not cause overload. Friends said that most likely it will not work to overload the operator. I would like someone to tell in more detail why it will not work this way and what the standard writes about this.

  • I would ask the teacher to show how he wants to call this operator. But then maybe he just wants a function of the form A b2a(B b){} - KoVadim

1 answer 1

The heir class itself can be copied to its base class, this is called truncation .

If you change inheritance to class B: private A { ,
then we will see a compilation error: 'A' is an inaccessible base of 'B' .
Those. the compiler tries to trim, and ignores the cast operator.

Conclusion - you can not write such a cast operator.

  • It turns out still possible. Just need to call differently. A a = b.operator A (); - moskalenco_a
  • trolleybus.zhpeg - Abyx
  • @Andrey Moskalenko easier to write a function. - Abyx