12-07-2022 07:34 AM
A simplified example of my problem.
Two classes, Class A and Class B.
Class B inherits from Class A.
Class A methods:
Class B methods:
Acquire Image *
* denotes overridden method
Is there a way at run time of determining whether an object is a member of Class B or not so that I know whether I can run the Get Temperature method (the code using this object will have controls that are of Class A)? The only ways I can see of doing it at the moment are:
Is there a better way/Am I just approaching inheritance wrong?
12-07-2022 10:53 AM - edited 12-07-2022 11:01 AM
Both ways you describe are perfectly valid solutions to your problem.
I would go with option 2 (to more specific + check error + run method if no error) because:
- It does not require Class A to have an empty method "Get Temperature". This method may not have sense for Class A.
- It works even if the object is a subclass of Class B;
- It does the check AND the cast at once, so you can directly use it with methods of Class B.
If you are worried about performance, you can also cast them once at the initialization of your application, and store them in a separate list of Class B objects.
I would do a benchmark with a big list of various objects (Class A and Class B mixed) to measure execution times. Maybe casting them each time you need it may be good enough...