tags:

views:

69

answers:

2

hello to everyone, if I have for example some class Base and derived from it Derived Also I have some list of shared pointers:

list<shared_ptr<Base> > list

I create shared pointer:

line 5    shared_ptr<Derived> ptr(new Derived(//some constructor));

my question is, can I do something like this:

list.push_back(ptr);

if Yes, can somebody explain why can I recieve an error (I receive this on the line 5)

no matching function for call to //here It writes me my constructor to Derived

thanks in advance for any help

+1  A: 

my question is, can I do something like this: list.push_back(ptr);

Yes - your problem has nothing to do with inheritance or smart pointers - you simply don't have the constructor declared you are trying to use.

A simple example that reproduces the error is:

struct X {};
X x(1);

Which gives you:

no matching function for call to 'X::X(int)'

You fix that by either constructing the instance differently or by adding the missing constructor:

struct X { X(int) {} };
Georg Fritzsche
A: 

You are trying to assign a value of type shared_ptr<Derived> to a container of shared_ptr<Base>. Try assigning pointer to Derived to shared_ptr<Base> and then adding that to the list<>:

class BASE {
 public:
  BASE() { }
  const char *name() const { return nameImpl(); }
 private:
  virtual const char *nameImpl() const { return "BASE"; }
};

class DERIVED : public BASE {
 public:
  DERIVED() { }
 private:
  virtual const char *nameImpl() const { return "DERIVED"; }
};


int main() {

 list< shared_ptr< BASE > > baseSequence;

 shared_ptr< BASE > basePtr(new BASE);
 baseSequence.push_back( basePtr );
 basePtr.reset(new DERIVED);
 baseSequence.push_back( basePtr );

 shared_ptr< DERIVED > derivedPtr(new DERIVED);
 baseSequence.push_back( derivedPtr ); 

 BOOST_FOREACH(const shared_ptr< BASE > &ptr, baseSequence) {
  cout << ptr->name() << "\n";
 }
 return 0;
}

`

John Watts
I guess your first sentence meant to say *"container of `shared_ptr<Base>`"*? This is fine, see e.g. the documentation: *"In particular, `shared_ptr<T>` is implicitly convertible [...] to `shared_ptr<U>` where `U` is an accessible base of `T`"*.
Georg Fritzsche
You're correct. I should have reviewed that example closer. Thanks.
John Watts