7

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.

2
  • At least add code that will compile and generate the errors you want us to fix. The code above has so many other syntax errors that solving your problem becomes irrelavant. Commented Jan 25, 2009 at 15:58
  • i agree with martin. if you want us to help you, invest some time in making your code c++ (not omitting return types, semicolons and other stuff) Commented Jan 25, 2009 at 16:29

1 Answer 1

15

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.

2
  • Question, is there any way around this, I come from the managed world, where this is allowed and I find it very useful, I don't really just wanna make these private things internal but if there's no way around it, I guess I have to. Is it possible to make the class a friend of itself? Commented Jan 19, 2012 at 7:50
  • John, either make f2 public or declare D to be a friend of B. I'm aware of no other way. Commented Jan 21, 2012 at 15:54