简体   繁体   中英

Override virtual protected method that is a friend of another class

Basically, I want to somehow simulate friendship inheritance with the restriction that it can only happen from inside a certain method.

So essentially, this is what I want

class A; // Forward declaration
class Base{
   friend class A; // friend declaration so that A is able to see protected methods

   protected:
   virtual void method() {// some definition, might also be pure virtual}

}

class Derived : public Base{
     A aObj;
     void method(){//override the one in base and also gain access to aObj private members.}
     public:
     //public interface
} 


class A {
    int var;
    friend void Base::method(); 
    public:
      // public interface
}

is there anyway to achieve this?

How about this

class Base {
   friend class A; 
   protected:
   virtual void method() = 0;
   std::tuple<int> GetAProperties(const A& a) {     
        // You can change the tuple params
        // as per your requirement.
        return std::make_tuple(a.var);
   }
}

class Derived : public Base {
    A aObj;
    void method() override {
        auto objProperties = GetAProperties(aObj);
    }
}

You could get pointer to private's A member in Base , and then pass these member pointers to the Derived :

class A; // Forward declaration
class Base{
   friend class A; // friend declaration so that A is able to see protected methods

   private:
   void method(A&);
   virtual void do_method(A& a,int A::* var) {// some definition, might also be pure virtual
     (a.*var)++;
   }

};
class A{
    int var;
    friend void Base::method(A&);
};
class Derived : public Base{
     A aObj;
     virtual void do_method(A& a,int A::* var) {// some definition, might also be pure virtual
     a.*var+=2;
   }
     public:
     //public interface
};

void Base::method(A& a){
       do_method(a,&A::var);
   }

NB: do not use it on the critical pass!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM