Jaege
Jaege

Reputation: 1873

C++ protected member inheritance

My question is why I cannot call protected virtual member function in derived class through a pointer to the base class unless declaring derived class as a friend of base class?

For example:

#include <iostream>

class A {
  friend class C;  // (1)
protected:
  virtual void foo() const = 0;
};

class B : public A {
  void foo() const override { std::cout << "B::foo" << std::endl; }
};

class C : public A {
  friend void bar(const C &);
public:
  C(A *aa) : a(aa) { }
private:
  void foo() const override {
    a->foo();       // (2) Compile Error if we comment out (1)
    //this->foo();  // (3) Compile OK, but this is not virtual call, and will cause infinite recursion
    std::cout << "C::foo" << std::endl;
  }
  A *a;
};

void bar(const C &c) {
  c.foo();
}

int main() {
  B b;
  C c(&b);
  bar(c);

  return 0;
}

The output is

B::foo
C::foo

In the above code, I want to call virtual function foo() through member a of class C (not the static bound one through this at compile time), but if I don't make C as A's friend, the call is illegal.

I think C is inherited from A, so that it can access the protected member of A, but why is it actually not happen?

Upvotes: 1

Views: 354

Answers (1)

Bo Persson
Bo Persson

Reputation: 92371

Class C can access the protected members of its own base class, but not members of any other A.

In your example, the parameter a is part of the totally unrelated class B to which C has no access rights (unless you make it a friend).

Upvotes: 5

Related Questions