fork download
  1. class X
  2. {
  3. public:
  4. X() {}
  5. void destroy() const { delete this; }
  6. protected:
  7. ~X() {}
  8. };
  9.  
  10. class Y : public X { }; // inheritance is ok
  11. class Z { X x; }; // syntax error, use pointer
  12.  
  13.  
  14. X x1; // syntax error
  15. int main()
  16. {
  17. X x2; // syntax error
  18. Y y1; // ok, would be syntax error if ~X() was private
  19. X* xp = new X; // ok
  20. Y* yp = new Y; // ok
  21.  
  22. delete xp; // syntax error
  23. xp->destroy(); // ok
  24. delete yp; // ok, would be syntax error if ~X() was private
  25. };
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.cpp: In function 'int main()':
prog.cpp:7:3: error: 'X::~X()' is protected
   ~X() {}
   ^
prog.cpp:17:7: error: within this context
     X x2;                  // syntax error
       ^
prog.cpp:7:3: error: 'X::~X()' is protected
   ~X() {}
   ^
prog.cpp:22:12: error: within this context
     delete xp;             // syntax error
            ^
prog.cpp: In function 'void __static_initialization_and_destruction_0(int, int)':
prog.cpp:7:3: error: 'X::~X()' is protected
   ~X() {}
   ^
prog.cpp:14:3: error: within this context
 X x1;                      // syntax error
   ^
stdout
Standard output is empty