Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

c++ - cannot call base class protected functions?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...