views:

848

answers:

1

I cant call protected function in my base class. Why? It looks something like this:

class B : B2
{
public:
  virtual f1(B*)=0;
protected:
  virtual f2(B*) { codehere(); }
}
class D : public B
{
public:
  virtual f1(B*b) { return f2(b); }
protected:
  virtual f2(B*b) { return b->f2(this); }
}

In msvc I get the error error C2248: 'name::class::f2' : cannot access protected member declared in class 'name::class'

In gcc I get error: 'virtual int name::class::f2()' is protected.

Why is that? I thought the point of protected members is for derived classes to call.

+8  A: 

Protected member functions can only be called inside the base class or in its derived class. You cannot call them outside your class. Outside calling means calling a member function of a class-typed variable.

So

virtual f1(B*b) { return f2(b); }

is ok, because f2 operates on the class itself. (called inside)

But

virtual f2(B*b) { return b->f2(this); }

won't compile, because f2 operates on b not the class D itself. (called outside) It's illegal.

To fix it B::f2 should be public.

Calmarius