I've just through a massive refactoring of a project to add a base class in place of what is now a derived class of said base class (because I want more "types" of this class).
My problem is, some of the utility functions take a reference of the original class A as a shared_ptr and so a function declaration looks as follows:
void UtilityClass::func(shared_ptr<A> &a);
But now that I have the new base class B and A is derived from B (as well as a new class C which is derived from B) I'm getting a compile-time error when I try and pass an instance of A or C to the function whose declaration is now:
void UtilityClass::func(shared_ptr<B> &b);
If I try and pass:
shared_ptr<A> a;
utilclass.func(a);
I get a compile-time error saying that (paraphrase):
Cannot convert parameter 1 from 'std::shared_ptr<_Ty>' to 'std::shared_ptr<_Ty>'
But I'm not sure how else I'd solve this problem, func() adds the A, B or C instance to a std::vector of shared_ptr values.
Thanks for your time.
EDIT: I also have another function that takes a reference so that it can assign a new instance of B to it and then return it.
The problem is that you're passing by non-const reference, which means you need the argument type to match exactly.
Change the function to take the pointer by value or const reference; then implicit conversions (such as shared_ptr<Derived> to shared_ptr<Base>) can be applied to the argument.
The following works without any problems and is a supported scenario:
#include <tchar.h>
#include <memory>
#include <iostream>
class Foo { };
class Bar : public Foo { };
int _tmain()
{
std::shared_ptr<Bar> b(new Bar());
std::cout << b.use_count() <<std::endl;
std::shared_ptr<Foo> f(b);
std::cout << b.use_count() <<std::endl;
std::cout << f.use_count() <<std::endl;
return 0;
}
If the classes are derived, no problems should occur.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With