Reputation: 3122
I have a key-value container class that holds pointers to heap-allocated objects of a base type. The insert method of the container instantiates one of 2 derived class objects (based on a runtime flag) and inserts it into itself.
I have a Find
method with the following signature:
bool Find(int key, Base *&result);
The classes that use of this container know which derived class is actually being stored, because there is a one-to-one mapping between a user of the class and one of the derived types.
So when a user tries to call the Find method as follows:
DerivedA *a = nullptr;
bool found = container.Find(10, a);
I get a compiler error saying that there is no matching function.
So it seems that implicit conversion isn't happening between the base and derived classes. I suspect it has to do with the fact that I'm passing the pointer by reference, but I'm not sure.
What is the "correct" way to achieve what I'm after here?
Thanks!
Upvotes: 1
Views: 2102
Reputation: 5954
Add an overload of Find
Base *pi=result;
bool r=Find(key,pi);
result=dynamic_cast<DerivedA *>(pi);
return r;
Upvotes: 0
Reputation: 32626
I suspect it has to do with the fact that I'm passing the pointer by reference
Imagine that Find
updates the passed pointer and now it points at a new instance of Base
. But the caller still interprets it as a pointer to DerivedA
.
Basically the issue is that you can assign
Base* basePtr = &derived;
but not the way around. So if the only guarantee of your Find
method is that it finds an instance of Base
type, we cannot just assign the pointer to it to DerivedA
.
If you do know that your Base
class pointer points at DerivedA
, you could consider dynamic_cast
:
Base* Find(int key);
....
DerivedA* a = dynamic_cast<DerivedA*>(Find(key));
(Returning the pointer might be better, as @juanchopanza comment suggests.)
Upvotes: 1