I want to make a non-static method that only constructors of the same class instance (or one of its subclasses) can call. Is there an elegant way to do this, except for a key-oriented access protection pattern?
class MyClass { public: void foo() { assert(foo was called from the constructor); //how?! if (some condition or other) throw ExceptionThatOnlyClientsThatConstructTheObjectCanHandle(); //hence my requirement } }; class MySubClass : public MyClass { public: MySubClass() { blah(); //correct use of foo() through blah() foo(); //correct use of foo() directly } void blah() { foo(); } //correctness depends on who called blah() }; int main() { MySubClass m; m.foo(); // incorrect use of foo() m.blah(); // incorrect use of foo() through blah() return 0; }
Edit: see my comments below, but I think this is either a special case of (1) transitive key-oriented access control, or (2) providing exception exclusions. Seeing this, the designer is a red herring.
source share