0

Let's say I have:

class Foo{
  void method();
}

And then I create:

class Bar : public Foo{

}

Where Bar has a lot of methods. Is there any clever way I can force all methods defined in Bar to call method() from Foo?

The reason I wish to do this is for some clever memoization. For certain function calls in Bar there can be some pre-processing to speed up future calls of that class by calling method(), thus I want to make a parent class Foo that invisibly handles the memoization, while the subclasses can happily and blindly focus purely on function definitions.

user650261
  • 2,115
  • 5
  • 24
  • 47
  • Invoking `method` in the constructor is not possible? Solve the problem quite neatly. – user4581301 Jul 03 '18 at 03:35
  • I don't see how that solves things. I want to call method as the first step of calling any method in Bar. Maybe there's a clever way to use the constructor to set this up, though. – user650261 Jul 03 '18 at 03:38
  • Need more information to give more details. Is the memoization done once, and then fixed? – user4581301 Jul 03 '18 at 03:57
  • The first time the method is called, a pre-processing procedure is called to speed up future evaluations. On future evaluations, that information (which no longer changes) should be used somehow to speed up the evaluation of the method. – user650261 Jul 03 '18 at 04:01
  • Then unless you have objects you ever use (and thus there is no point to computing the cached values) you might as well add the memoization to the `Foo` constructor. All of the work caching is done when you create the object and is all ready to use as soon as you call any of the methods. – user4581301 Jul 03 '18 at 04:05
  • The memoization needs to be done once per function, not once per object. – user650261 Jul 03 '18 at 04:09
  • Ah. Recommend an edit to the question to make that clear. In that case, no. I don't have a good suggestion. The only things I can come up with are more difficult or confusing than calling the appropriate memoization method. Pity there is such thing as a per-object `static` local variable. That's exactly what you want. – user4581301 Jul 03 '18 at 04:25
  • 1
    Do all the methods of `Bar` have to call the same method of `Foo` ? If so, the [Excute-Around](https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Execute-Around_Pointer) pattern might be interesting. See [this question/answer](https://stackoverflow.com/a/42020373) for implementation suggestions. – Vincent Saulue-Laborde Jul 03 '18 at 08:54
  • Interesting - this sounds exactly what I'm looking for. I'll look at this soon. Thanks! – user650261 Jul 03 '18 at 21:06

0 Answers0