Downcasting interface references - casting

I'm getting a run-time exception when I try to cast an object to an interface that I'm pretty sure it implements.
I have the following interfaces:
public interface class ISMILTimeContainer;
public interface class ISMILSequence : ISMILTimeContainer;
public interface class ISMILParallel : ISMILTimeContainer;
I have the following classes:
ref class TimeContainer : public ISMILTimeContainer;
ref class Sequence : public TimeContainer, ISMILSequence;
ref class Parallel : public TimeContainer, ISMILParallel;
Then, I try the following:
ISMILTimeContainer^ container = getSequence(); // returns a Sequence^
ISMILSequence^ sequence = static_cast<ISMILSequence^>(container);
This throws an exception at run-time:
Platform::InvalidCastException ^ at memory location 0x04AFD83C.
HRESULT:0x80004002 No such interface supported
As far as I can tell, this should be working. Is there something wrong with what I'm trying to do, or do the symptoms indicate an implementation issue (something is different than what is claimed above)?

Your container is an ISMILTimeContainer created by implicit cast. This is upcasting, casting a derived class object (the return value of getSequence(), a Sequence) to a parent or base class object (the ISMILTimeContainer).
When you then try to downcast to an ISMILSequence in your next statement, because you have an inheritance chain, you pass compiler checks using static_cast<ISMILSequence^>.
However, C++/CX also runs runtime checks [1], and in this case it seems that your container variable, of type ISMILTimeContainer, does not have all of the information required to form an ISMILSequence in your second statement. Although an ISMILSequence IS-A ISMILTimeContainer, the opposite is not true.
For information about up-casting and down-casting, see [2] or other google results. The later sections in this blog post might be of help.

Related

Variable types from inherited classes

If I have a class that inherits from a base class, can I use that base class as a variable type in c++?
class Component {
// Code here
};
class TransformComponent : public Component {
// Code here
};
class Entity {
// Code here
Component *getComponent(Component *searchComponent) {
// Code Here
}
};
as you can see here, I am using the base class "Component" as a return type and a variable type. The problem is that the user may input a "TransformComponent". The only reason I am asking this is because the "TransformComponent" class inherits from the "Component" class and there might be a way to do this?
<Entity>.getComponent(Component &TransformComponent());
The answer I'm looking for is one that works both for the return type, and the variable type.
Absolutely! It's one of the beauties of OOP. Your instanced class of type TransformComponent is both an instance of Component as well as TransformComponent.
If you had some function that returned a type of Component, this could return any class derived from Component as a Component! If you later wanted to refer to it as its sub-class, you might have to check its type and then cast to it, but what you want is absolutely possible, and you're going the right way about it.
In fact, in the example you describe, were you are using Component and the user might pass a TransformComponent, all of the base methods and properties that the Component possesses will be possessed by TransformComponent too. It will look and feel as if it was a Component, with all the benefits of being one.
The only time a problem will arise is if you specifically want to access the features of a TransformComponent, and the user passed a Component. The parent class doesn't know about the sub-class stuff, because it isn't an instance of one, it will throw up errors for you. Sub-classes build upon the base class, so they have all the base-class stuff, plus more. Basically its only an issue when your example is reversed.
Your Entity.getComponent() method suggests that it only cares that the provided argument is a Component ... not any specialization, such as TransformComponent, of that original class.
So, if you find yourself writing logic that actually cares that "this Component might actually be a TransformComponent," then "warning bells should be going off." Create method definitions within the class that are as specific as possible.

LOKI C++: How does 'ScatterHierarchyTag' solve the inheritance ambiguity?

I am going through Chapter 3 of Alexandrescu's Modern C++ Design. It explains the implementation of HierarchyGenerators.h, however changes have been made to the library since then.
I am unable to understand how the ScatterHierarchyTag solves the ambiguity in resolving Field function (the function allows us to access members defined by particular Base<type>, for example Field<int>(Object) would get us a &Base<int> to Object), when the typelist used to generate hierarchy has duplicates. (ex: GenScatterHierarchy<TYPELIST_4(int,int,string,Widget), Base> Object) I see that it adds a unique "type/tag" in each of the branches, right before the root Base<type> class, but still ambiguity is there right?
Thank you in advance.
EDIT:
Chart showing multiple inheritance issue with repeated types in typelist.
GSH = GenScatterdHierarchy
I believe the unique tags are inserted seperately, for each of the two connections to Base<int> (marked one by blue line) (same goes for other base classes at root)
Also, I inserted picture to make it easier for everyone to understand. Let me know if it does not fit in stackoverflow's guidelines and I shall remove it.
ScatterHierarchyTag is not removing ambiguity. What it does, is making an ambiguous base class accessible.
Consider the following class hierarchy:
class A {};
class B : public A {};
class C : public A, public B {};
Class C contains two copies of class A (it makes more sense when A is not empty :), one is created because of direct inheritance, another — because of indirect inheritance through B. You can access the second instance converting to B first:
A &indirect_base = static_cast<B>(C_instance);
For the other instance, there is simply no way of accessing it. Because of that, it is called "inaccessible base".
This example embeds naturally in class hierarchy created by GenScatterHierarchy:
GenScatterHierarchy<int, Base> is A,
GenScatterHierarchy<TYPELIST_3(int,string,Widget)> is B,
GenScatterHierarchy(TYPELIST_4(int,int,string,Widget)) is C.
So, instance of Base<int> created for the first int in type list is an inaccessible base. However, if ScatterHierarchyTag is added, we can access it by casting to GenScatterHierarchy<ScatterHierarchyTag<int, TYPELIST_3(int,string,Widget)>, Base> first.

Casting to subclass from a collection of base pointers

I need to model a service retriever class to retrieve various services.
Suppose you have a collection of Services, each Service retrievable with a unique string key
(eg. : Services.getService("render"); should retrieve the service indexed as "render").
Now, Service is the base class of various *Service inherited classes, like RenderService, InputService et al. , each one with their different methods.
Now, this could be simply modeled with a std::unordered_map<std::string, Service*>, but it returns a pointer to the base class and not to the derived class (so far, it's pretty obvious). This means I can't automatically call the requested service's methods without doing an explicit cast, I must write something like: ((RenderService*)Services.at("render"))->callRenderServiceMethod();.
This is pretty ugly and redundant, because the at method key is logically linked to RenderService.
I could skirt around the problem by declaring:
#define CALL_RENDER ((RenderService*)Services.at("render"))
and using it as
CALL_RENDER->callRenderServiceMethod();
Although it looks like a clever "hack", it's not the right way to solve this problem.
I've also tried to do something like getService<RenderService>("render"); but it doesnt work well and the redundancy problem is still there.
In the end, I'm doing this because I'd like to avoid this :
class Services
{
public:
RenderService& getRenderService();
AudioService& getAudioService();
AnotherInheritedService& getAnotherInheritedService();
private:
RenderService _renderService;
AudioService _audioService;
AnotherInheritedService _anotherInheritedService;
};
What kind of approach should I use for this kind of problem?
From what I understand from the problem, you need the functions to be declared as virtual functions.
Declaring a function virtual in the base class definition and implementing that function in each derived class will allow the appropriate class' function to be called based on the type of class pointer.
Now, I don't understand why you only have pointers to the base class only. Logically, the pointers you're getting from unordered_map are being returned should be actually derived class pointers but only being "upcasted" to a base class pointer.

How to get the right pointer "alignment" in case of multiple inheritance in C++?

Say I have two interfaces IFoo, and IBar; plus a concrete type FooBar implementing these interfaces:
class FooBar : public IFoo, public IBar
{
//FooBar stuff
};
Somewhere I get a void* pointer, pointing on a FooBar instance.
void* fooBar = getOrCreateStuff();
Now I want to get a pointer on IBar from my fooBar instance.
IBar* iBar = static_cast< IBar* >(fooBar);
Unfortunately, iBar is not pointing on the right memory address. The example is silly on purpose -- in the real life, I don't know the concrete type I am pointing to.
EDIT: I am writing an API where I expose template <class StuffT> StuffT getOrCreateStuff() method. At this point, there is absolutely no way to know what type devs are using. The above example is showing you guys the way this method is supposed to be used. We register a concrete type in the API and get it back as an interface. It works like a charm when dealing with single inheritance, but multiple-inheritance is more complicated.
Any idea to get my iBar pointing on the working address offset?
If you don't know what you are pointing to you are out of luck! With static_cast(v) where "v" is of type "void*" you can only cast to the type "T*" if "v" resulted from an implicit conversion to "void*". If you really get a "void*" you'll need to first restore a type "B*" (e.g. some sort of base class; it doesn't have to be a common base class of all branches, just known to be present) which has at least one virtual function (e.g. its destructor if there isn't any functionality you want there) and from there you can use dynamic_cast(b) to restore some type somewhere in the inheritance hierarchy. Note that even this doesn't necessarily work if there are multiple "T" subobjects in the actual object.
The reason all this is necessary is that in an object using multiple inheritance the pointers to subobjects are getting adjusted: depending in which branch you are, the same subobject may exist and dealing with a specific one requires a different pointer. You can avoid the use of dynamic_cast(b) but only if you effectively create your own run-time information system.
Change getOrCreateStuff() to return something other than void*. If it returns IStuff*, and FooBar derives from IStuff, then you can use dynamic_cast to get to IBar*.
if you are sure of :"Somewhere I get a void* pointer, pointing on a FooBar instance."
then, this is a solution :
IBar* iBar = static_cast<IBar*>(reinterpret_cast< FooBar* >(fooBar));
or :
IBar* iBar = dynamic_cast<IBar*>(reinterpret_cast< FooBar* >(fooBar));
as IBar is an interface, it must have a pure virtual method, so it is polymorphic, so dynamic cast an be used.

How to have a generic type inherit from a generic type

I have an abstract class:
public abstract class LMManager<ENTITY, ILM_ENTITY> where ENTITY : ILM_ENTITY, IActiveRecord, ICallOnCreated, new( )
ENTITY is some kind of DataObject, ILM_ENTITY, IActiveRecord, and ICallOnCreated are interfaces that the DataObject implements.
Typically, I subclass this guy with classes something like
public class JobManager : LMManager<Job, ILMJob>
public class JobViewManager : LMManager<vwJob, ILMJobView>
Now, I have a case where two of the sub-classes have some code in common, so I want to insert another layer in between, something like
public abstract class JobManagerBase : LMManager<ENTITY, ILM_ENTITY>
and then change the other two guys to
public class JobManager : JobManagerBase<Job, ILMJob>
public class JobViewManager : JobManagerBase<vwJob, ILMJobView>
In the definition of my JobManagerBase, I get four errors related to ENTITY:
Must be a non-abstract type with a public parameterless constructor
No boxing conversion or type parameter conversion from ENTITY to ICallOnCreated
No boxing conversion or type parameter conversion from ENTITY to IActiveRecord
No boxing conversion or type parameter conversion from ENTITY to ILM_ENTITY
Is it terribly obvious what I am missing?
Your JobManagerBase attempts to use LMManager with the parameters ENTITY and ILM_ENTITY.
Since these parameters do not meet your constraints, you get an error. (What if someone makes a JobManagerBase<int, string>?)
You need to add generic parameters and the same where clause to JobManagerBase to ensure that its parameters meet the constraints required for LMManager.