Search code examples
c++oopinheritancefriend

C++ Call private / protected function of a common base class


Is there a nice way to call A::foo() from B::bar() in the following sample?

class A {
protected:
  void foo() {}
};

class B : public A {
public:
  void bar(A& a) { // edit: called with &a != this
    a.foo(); // does not work
  }
};

I can't think of anything other than declaring B to be a friend of A, but that could get pretty ugly with some more classes.

Any ideas?


Solution

  • Yes, you can use a base-class function.

    class A {
    protected:
      void foo() {}
      void do_other_foo(A& ref) {
          ref.foo();
      }
    };
    
    class B : public A {
    public:
      void bar(A& a) { // edit: called with &a != this
        this->do_other_foo(a);
      }
    };