javac++matlabooptemplate-method-pattern

Method only accessible from super-classes (C++ and other languages)


Suppose I have a super class that offers a public template method. Subclasses will have to implement some sub-operations. How do I declare this sub-ops to make sure they can only be called from SuperClass? There's protected, but that works the other way round as far as I know: Subclasses can access protected superclass members. I want to allow a superclasses (and only superclasses!) to call subclass members.

class SuperClass{
    public:
      void templateMethod(){
         this->op1();
         this->op2();
      } 

      // how to declare these? public? protected?
      virtual void op1() = 0;
      virtual void op2() = 0;
}

class SubClass : public SuperClass{
      // how to declare these? public? protected?
      virtual void op1() { ... };
      virtual void op2() { ... };
} 

I'm currently working in C++ and Matlab, but I'd also be very interested in some general remarks considering other languages.


Solution

  • In C++, you can achieve your aim by making op1 and op2 private in all classes. This technique is idiomatic in C++.

    A base class will access the private function in a child class through the v-table that is set up when an object is instantiated.

    Of course, there is nothing stopping another function in your child class from calling a function marked private in that child class. If you want wanted to do that, then the child class would not be the correct place for the function.

    The same can be said for Java, except, of course that virtual is automatic.