0

I'm using an home made shared_from_this class (CEnableSharedFromThis) because I'm under C++03 and I can't use boost on my project.

I have a class A which look like this :

class A : virtual CEnableSharedFromThis<A>
{
...
}

and class B like that :

class B : public A, virtual CEnableSharedFromThis<A>
{
   void foo()
   {
      Poco::SharedPtr<B> b(sharedFromthis());
   }
}

I see some people that have an error with an ambigous method. So I use virtual inheritance and I don't have this error.

But I have a new one that I can't give up in the foo() method.

The compiler says :

error: cannot convert from base CEnableSharedFromThis<A> to derived type A via virtual base CEnableSharedFromThis<A>

So I try the following foo() method :

   void foo()
   {
      Poco::SharedPtr<B> b(B::sharedFromthis());
   }

But it changes nothing.

Any idea ?

EDIT :

Following your recommandations I remove the inheritance of CEnableSharedFromThis of B and change foo() function like that :

class B : public A
{
   void foo()
   {
      Poco::SharedPtr<B> b(sharedFromthis().cast<B>());
   }
}
Puppy
  • 144,682
  • 38
  • 256
  • 465
lgm42
  • 591
  • 1
  • 6
  • 29
  • 1
    shouldn't it be `class B : public A, virtual CEnableSharedFromThis`? – m.s. Jun 12 '15 at 14:16
  • @m.s. but what would the virtual inheritance do, then? They're completely different classes, no? – Ami Tavory Jun 12 '15 at 14:18
  • 1
    the virtual inheritance should not be necessary at all (neither for `A` nor for `B`). Only `A` should inherit from `CEnableSharedFromThis` (see [this SO question](http://stackoverflow.com/questions/4491420/enable-shared-from-this-and-inheritance)); virtual inheritance would be necessary if you have multiple inheritance (see [this SO question](http://stackoverflow.com/questions/16082785/use-of-enable-shared-from-this-with-multiple-inheritance)) – m.s. Jun 12 '15 at 14:29
  • In my case, The caller must get an instance of B and not A. so If I remove the inheritance from CEnableSharedFromThis of B I only get a shardePtr of A and not B – lgm42 Jun 15 '15 at 08:12
  • You can use static_pointer_cast to cast up the pointer. – Puppy Jun 15 '15 at 13:17

1 Answers1

0

Override it and use static_pointer_cast instead.

class B : public A
{
   Poco::SharedPtr<B> sharedFromThis() {
       return Poco::StaticPointerCast<B>(CEnableSharedFromThis<A>::sharedFromThis());
   }
   void foo()
   {
      Poco::SharedPtr<B> b(sharedFromthis());
   }
}

This is assuming the existence of an analogous Poco::StaticPointerCast to std::static_pointer_cast.

Puppy
  • 144,682
  • 38
  • 256
  • 465