fork download
  1.  
  2. #include <cassert>
  3. #include <iostream>
  4. #include <memory>
  5.  
  6. using namespace std;
  7.  
  8.  
  9. enum class ObjectCategory
  10. {
  11. none,
  12. XObject,
  13. YObject,
  14. XYObject
  15. };
  16.  
  17.  
  18. class ObjectBase:
  19. public enable_shared_from_this< ObjectBase >
  20. {
  21. public:
  22.  
  23. ObjectBase() {}
  24.  
  25. virtual ~ObjectBase() {}
  26.  
  27. virtual ObjectCategory Category() const = 0;
  28.  
  29. };
  30.  
  31. class XObject:
  32. public virtual ObjectBase
  33. {
  34. public:
  35.  
  36. XObject() {}
  37.  
  38. ~XObject() {}
  39.  
  40. ObjectCategory Category() const override
  41. {
  42. return ObjectCategory::XObject;
  43. }
  44.  
  45. };
  46.  
  47. int main()
  48. {
  49. typedef shared_ptr< ObjectBase > ObjectPtr;
  50.  
  51. ObjectPtr p1 = make_shared< XObject >();
  52. assert( ObjectCategory::XObject == p1->Category() );
  53.  
  54. auto x1 = static_pointer_cast< XObject, ObjectBase >( p1 );
  55. assert( x1 );
  56.  
  57. return EXIT_SUCCESS;
  58. }
  59.  
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
In file included from /usr/include/c++/6/memory:82:0,
                 from prog.cpp:4:
/usr/include/c++/6/bits/shared_ptr.h: In instantiation of ‘std::shared_ptr<_Tp1> std::static_pointer_cast(const std::shared_ptr<_Tp2>&) [with _Tp = XObject; _Tp1 = ObjectBase]’:
prog.cpp:54:59:   required from here
/usr/include/c++/6/bits/shared_ptr.h:447:35: error: cannot convert from pointer to base class ‘ObjectBase’ to pointer to derived class ‘XObject’ because the base is virtual
     { return shared_ptr<_Tp>(__r, static_cast<_Tp*>(__r.get())); }
                                   ^~~~~~~~~~~~~~~~~~~~~~~~~~~~
stdout
Standard output is empty