In C++ for Windows, I have some object factory that is supposed to create a series of Info object by passing a pointer to the object to a Create function and returning a created object.
void CreateInfoObject(AbstractInfo** info); // The creation function
AbstractInfo is a base class of which we have many types of Info objects derive.
I thought I could now create an Info object as follows:
MyInfoObject* InfoObj = NULL; // derived from AbstractInfo object
InfoFactory fc;
fc.CreateInfoObject(&InfoObj); // Now I want to get my initialized pointer back
But it says it cannot do the cast… What is wrong?
ERROR:
Cannot cast from MyInfoObject**_W64 to AbstractInfo**
EDIT: The first answer mentions that the interface is horrid, cannot see who’s allocating etc… How can I improve?
Let’s think about a possible implementation of
CreateInfoObject:Now,
SuperInfoandMyInfoObjectdo not have anything in common right ?This is why, in general, the following is forbidden:
As it would allow
D1to point to something unrelated.There are several solutions:
Then, if you know with certainty that you have, in fact, a
MyInfoObjectyou can use:or if you are unsure:
which will set
myInfotonullptrif ever theinfodid not pointed to an instance ofMyInfoObject(or derived).Bear in mind though, that your interface is really horrid. It very C-ish and it is unclear whether memory is actually allocated or not… and who is responsible for handling it if it is.
EDIT:
In good C++ style, we use RAII to both denote ownership and ensure clean-up. RAII is well-known though not very indicative, I myself prefer the newish SBRM (Scope Bound Resources Management).
The idea is that instead of using a bare pointer, which does not indicate anything about ownership (ie do you have to call delete on it ?) you should use a smart pointer, like for example
unique_ptr.You can also make use of the return parameter of the method, to avoid having a two-steps initialization process (first create the pointer, then make it point to an object). Here is a concise example:
Here, there is no ambiguity in regard to the ownership.
Also, note how you better understand your question here:
would not compile because you cannot convert a
AbstractInfo*to aMyInfoObject*without usingstatic_castordynamic_cast.