c++ – Overloading the cast operator to the base class


They suddenly demanded in a derived class to overload the cast operator into the base one (this is a lab, I wouldn't do that myself).

#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;

At startup, it does not output anything – that is, it does not cause an overload. Friends said that most likely it would not work to overload the operator like that. I would like someone to tell in more detail why this does not work out and what the standard writes about this.


The inherited class can itself be copied into its base class, this is called slicing .

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

Conclusion – you cannot write such a cast operator.

Scroll to Top