0

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?

GamefanA
  • 1,555
  • 2
  • 16
  • 23
  • Please read the question, I am not interested in calling `method` from inside A, I want to allow derived classes of `base`to access A's private members from within specific methods. – GamefanA Aug 18 '18 at 19:16
  • Why do you put so many restrictions? – Oliv Aug 18 '18 at 19:20
  • Because I only want derived classes of base to have access to A's private members without having to manually insert a friend declaration into A every time I derive from Base – GamefanA Aug 18 '18 at 19:24
  • In derived class, `A` member have to be defined as `A*` to avoid the `non complete class` compiler's error. – Coral Kashri Aug 18 '18 at 19:27
  • Not sure I understand 100% what you are looking for, I just posted a possible answer, do not hesitate to tell that this is not what you are looking for. – Oliv Aug 18 '18 at 19:33

2 Answers2

1

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);
    }
}
cplusplusrat
  • 1,435
  • 12
  • 27
0

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!!

Oliv
  • 17,610
  • 1
  • 29
  • 72