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 vecA(7);
localA = globalA;
*ptrA = localA;
}