Is there any way to know if we are calling inside the constructor?

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.

+4
source share
1 answer

Not. This is not possible without specifying any other variable. The best you can do is make private methods so that only your class can call it. Then make sure that only the constructor calls it. Besides this, do you want the constructor calling it not to try to use the function and just put the code there?

+5
source

Source: https://habr.com/ru/post/1493487/


All Articles