简体   繁体   中英

Passing derived class pointer to function expecting base pointer by reference

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!

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.)

Add an overload of Find

Base *pi=result;
bool r=Find(key,pi);
result=dynamic_cast<DerivedA *>(pi);
return r;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM