K
K
Kalombyr2018-01-30 13:27:09
C++ / C#
Kalombyr, 2018-01-30 13:27:09

Pointer type casting, how to overload?

Good afternoon!
For example, there is a class MyClass and its interface IInterface
if you do:

MyClass * myClass = new MyClass();
IInterface * interface;

What would lead to the type IInterface is quite simple:
interface = myClass;
But on the contrary, you will have to explicitly prescribe: What can be done so that you do not have to prescribe it? That is, you just need static_cast and you can’t override the rest of the castes, because ... I started thinking about operator overloading But in the case of pointers, this certainly does not work. How can you do?
myClass = static_cast<MyClass*>(interface);
myClass = interface;
explicit operator IInterface*()

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mercury13, 2018-01-30
@Mercury13

There is a special operation for this, dynamic_cast.
If interface is not MyClass, then it will return NULL.
If through dynamic_cast we assign not pointers, but links, the std::bad_cast crash will be thrown.
UPD. Such downcasts are a compromise between OOP and the reality that forces us to simplify interfaces. For example, in C++Builder

int __fastcall SomeObject::ButtonClick(TObject* Sender)
{
  TButton* button = dynamic_cast<TButton*>(Sender);
  ...
}

V
Vitaly, 2018-01-30
@vt4a2h

In general, if for some reason you need to convert down the class hierarchy, then this is a sign of bad architecture, because. dependencies are being passed incorrectly, or interfaces are allocated incorrectly, or you are somehow working with the library incorrectly. Although, of course, there are exceptions, but they are few.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question