The access for a virtual function is specified when it is declared. The access rules for a virtual function are not affected by the access rules for the function that later overrides the virtual function. In general, the access of the overriding member function is not known.
If a virtual function is called with a pointer or reference to a class object, the type of the class object is not used to determine the access of the virtual function. Instead, the type of the pointer or reference to the class object is used.
In the following example, when the function f() is called using a pointer having type B*, bptr is used to determine the access to the function f(). Although the definition of f() defined in class D is executed, the access of the member function f() in class B is used. When the function f() is called using a pointer having type D*, dptr is used to determine the access to the function f(). This call produces an error because f() is declared private in class D.
class B {
public:
virtual void f();
};
class D : public B {
private:
void f();
};
int main() {
D dobj;
B* bptr = &dobj;
D* dptr = &dobj;
// valid, virtual B::f() is public,
// D::f() is called
bptr->f();
// error, D::f() is private
dptr->f();
}
本文探讨了C++中虚拟函数的访问规则。当通过基类指针调用派生类的虚拟函数时,其访问权限取决于指针的类型而非对象的实际类型。文章通过具体示例解释了这一概念,并展示了如何避免因访问权限不当而导致的编译错误。
554

被折叠的 条评论
为什么被折叠?



