Search code examples
c++inheritanceoverridingfriend

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?


Solution

  • 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);
        }
    }