3

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?

PiotrNycz
  • 23,099
  • 7
  • 66
  • 112
Jared Hoberock
  • 11,118
  • 3
  • 40
  • 76

1 Answers1

2

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;
}
Community
  • 1
  • 1
PiotrNycz
  • 23,099
  • 7
  • 66
  • 112