code_junkie

Using “super” in C++

Nov 11th, 2011
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. class Derived : public Base
  2. {
  3. public :
  4. typedef Base super; // note that it could be hidden in
  5. // protected/private section, instead
  6.  
  7. // Etc.
  8. } ;
  9.  
  10. Derived(int i, int j)
  11. : super(i), J(j)
  12. {
  13. }
  14.  
  15. void Derived::foo()
  16. {
  17. super::foo() ;
  18.  
  19. // ... And then, do something else
  20. }
  21.  
  22. class DerivedDerived : public Derived
  23. {
  24. public :
  25. typedef Derived super; // note that it could be hidden in
  26. // protected/private section, instead
  27.  
  28. // Etc.
  29. } ;
  30.  
  31. void DerivedDerived::bar()
  32. {
  33. super::bar() ; // will call Derived::bar
  34. super::super::bar ; // will call Base::bar
  35.  
  36. // ... And then, do something else
  37. }
  38.  
  39. class MyClass : public MyBase
  40. {
  41. private: // Prevents erroneous use by other classes.
  42. typedef MyBase inherited;
  43. ...
  44.  
  45. class Base
  46. {
  47. public: virtual void foo() { ... }
  48. };
  49.  
  50. class Derived: public Base
  51. {
  52. public:
  53. typedef Base super;
  54. virtual void foo()
  55. {
  56. super::foo(); // call superclass implementation
  57.  
  58. // do other stuff
  59. ...
  60. }
  61. };
  62.  
  63. class DerivedAgain: public Derived
  64. {
  65. public:
  66. virtual void foo()
  67. {
  68. // Call superclass function
  69. super::foo(); // oops, calls Base::foo() rather than Derived::foo()
  70.  
  71. ...
  72. }
  73. };
  74.  
  75. template <typename TText, typename TSpec>
  76. class Finder<Index<TText, PizzaChili<TSpec> >, PizzaChiliFinder>
  77. : public Finder<Index<TText, PizzaChili<TSpec> >, Default>
  78. {
  79. typedef Finder<Index<TText, PizzaChili<TSpec> >, Default> TBase;
  80. // …
  81. }
  82.  
  83. template <typename T, size_t C, typename U>
  84. class A
  85. { ... };
  86.  
  87. template <typename T>
  88. class B : public A<T,99,T>
  89. { ... };
  90.  
  91. template <class C>
  92. struct MakeAlias : C
  93. {
  94. typedef C BaseAlias;
  95. };
  96.  
  97. class Derived : public Base
  98. {
  99. private:
  100. typedef Base Super;
  101. };
  102.  
  103. class Derived : public MakeBaseAlias<Base>
  104. {
  105. // Can refer to Base as BaseAlias here
  106. };
Add Comment
Please, Sign In to add comment