How to prevent derivation from a type in c++03? [duplicate]

北城以北 提交于 2019-12-01 05:44:47

问题


C++11 introduces keyword final, which makes it illegal to derive from a type.

Is there a way to achieve a similar result with C++03, perhaps by making certain member functions private?


回答1:


There are two solutions for C++03:


First solution: private virtual friend base class with private default constructor:

Based on this answer, with the difference that template are not used - thus we can make virtual base class a friend to "final" class.

class A;
class MakeAFinal {
private: 
  MakeAFinal() {}   
  // just to be sure none uses copy ctor to hack this solution!
  MakeAFinal(const MakeAFinal&) {}   
  friend class A;
};

class A : private virtual MakeAFinal {
// ...
};

Frankly I did not like this solutions, because it adds the unnecessary virtual-ism. All this can be enclosed in macros, to increase readability and easiness of usage:

#define PREPARE_CLASS_FINALIZATION(CN) \
  class CN; \
  class Make##CN##Final { \
    Make##CN##Final() {} \
    Make##CN##Final(const Make##CN##Final&) {} \
    friend class CN; }

#define MAKE_CLASS_FINAL(CN) private virtual Make##CN##Final

PREPARE_CLASS_FINALIZATION(A);
class A : MAKE_CLASS_FINAL(A) {
// ...
};

Second solution: all constructors are private (including copy constructor). Instances of the class are created with help of friend class:

class AInstance;
class A {
// ...
private:
// make all A constructors private (including copy constructor) to achieve A is final
  A() {}
  A(const A&) {} // if you like to prevent copying - achieve this in AFinal
  // ...
  friend class AInstance;
};
struct AInstance {
  AInstance() : obj() {}
  AInstance(const AInstance& other) : obj(other.obj) {}
  // and all other constructors
  A obj;
};

// usage:
AInstance globalA;
int main() {
  AInstance localA;
  AInstance ptrA = new AInstance();
  std::vector<AInstance> vecA(7);
  localA = globalA;
  *ptrA = localA;
}


来源:https://stackoverflow.com/questions/10746499/how-to-prevent-derivation-from-a-type-in-c03

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!