I need to get an exception when converting a pointer to a class A object to a pointer to a class B object, but the compiler does not allow overloading

#include <iostream> using namespace std; class A { protected: int a; public: A operator B*()(A *ax) //Тут выдает ошибку,говорит,что B не имя типа { throw("Bad Type Overload"); } }; class B:public A { protected: int B; }; int main() { A *a; B *b; b=(B*)a; return 0; } 
  • does he even know what class B is? can try to specify through a class that this is a class? And yes, but are you sure that this is normal when the parent knows about the heir? - pavel
  • @pavel Well, here he doesn’t need to know about the heir, he only needs to know that he is led to that type - andybelous2

1 answer 1

To begin with, what is B in the line with the operator is unknown.

Further, the cast operator has no return type (it is already specified in the operator!), And does not receive any parameter - it already receives this ...

Member int B; in class B also not good.

Coercion b=(B*)a will not even try to use your operator - because this is a pointer casting to a pointer (in parentheses - terrible: a pointer to the base class to a pointer to the derived ...)

So the best you can get is about

 class B; class A { protected: int a; public: operator B*() { throw("Bad Type Overload"); } }; class B:public A { protected: int b; }; int main() { A *a; (B*)*a; return 0; } 

but all this is not a very healthy occupation, and it is not clear to whom and why it is necessary ...

Update
Here, take a look - you can get an exception, but when bringing links.

 #include <iostream> using namespace std; class Base { public: virtual ~Base() {} }; class Derived: public Base { public: virtual ~Derived() {} }; int main() { Base * b = new Base; Derived * d = dynamic_cast<Derived *>(b); cout << d << endl; try { Base bb; Derived & dd = dynamic_cast<Derived &>(bb); } catch(exception&e) { cout << e.what() << endl; } } 
  • It's just that my task consists of this, you need to handle an exception, when the base class pointer is brought to the pointer to the heir, and I thought that overload must be done here - andybelous2
  • @ andybelous2 even so it will be possible to bring. ideone.com/maTeIf - pavel
  • What should I do then? As I need exactly the conversion of the pointer to the pointer - andybelous2
  • @pavel does not issue exception so - andybelous2
  • one
    The handler can be defined, only this is the exception who will generate it ... ... - Harry