#include <iostream>
#include <memory>
class Base{
};
class Derive : public Base{
};
void foo(std::shared_ptr<Base>& p){
}
void bar(const std::shared_ptr<Base>& p){
}
int main(){
auto base = std::make_shared<Base>();
foo(base);
bar(base);
auto derive = std::make_shared<Derive>();
foo(derive);
bar(derive);
return 0;
}
g++ -std=c++0x test.cpp
The compiler says:
test.cpp:21:5: error: no matching function for call to 'foo'
foo(derive);
^~~
test.cpp:9:6: note: candidate function not viable: no known conversion from 'std::__1::shared_ptr<Derive>' to
'std::shared_ptr<Base> &' for 1st argument
void foo(std::shared_ptr<Base>& p){
Could you explain why you can't pass the shared_ptr of derived class to foo(), while you can pass it to bar() that receives const reference of the shared_ptr.
Sorry for my poor English. Thanks.