I have :
class Foo { public: void log() { } void a() { log(); } void b() { log(); } };
Is there a way that I can have each method of Foo
, call log()
, but without me having to explicitly type log() as the first line of each function ? I want to do this, so that I can add behaviour to each function without having to go through each function and make sure the call is made, and also so that when I add new functions, the code is automatically added...
Is this even possible ? I can't imagine how to do this with macro's, so not sure where to begin... The only way I have thought of so far, is to add a "pre-build step", so that before compiling I scan the file and edit the source code, but that doesn't seem very intelligent....
EDIT: Just to clarify - I don't want log() to call itself obviously. It doesn't need to be part of the class.
EDIT: I would prefer using methods that would work cross platform, and using only the stl.
Recursion is a method that call itself. In this case it is a recursion.
In this program, you have to first make a class name 'CallingMethodsInSameClass' inside which you call the main() method. This main() method is further calling the Method1() and Method2(). Now you can call this as a method definition which is performing a call to another lists of method.
Java does not support “directly” nested methods. Many functional programming languages support method within method. But you can achieve nested method functionality in Java 7 or older version by define local classes, class within method so this does compile.
Calling a private method from another ClassA private method can be called from another Class by using reflection API. A private method has more accessibility restrictions than other methods. A private method can be accessed from another class using getDeclaredMethod(), setAccessible() and invoke() methods of the java.
Thanks to the unusual properties of operator ->
, we can inject code before any member access, at the expense of a slightly bent syntax:
// Nothing special in Foo struct Foo { void a() { } void b() { } void c() { } }; struct LoggingFoo : private Foo { void log() const { } // Here comes the trick Foo const *operator -> () const { log(); return this; } Foo *operator -> () { log(); return this; } };
Usage looks as follows:
LoggingFoo f; f->a();
See it live on Coliru
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With