派生类Private方法被调用 [英] Derived class Private method is getting called
问题描述
我有一个指向派生类对象的基类指针.方法foo()在基类中是公共的,但在派生类中是私有的.基类foo()是虚拟的.因此,当我从基类指针调用foo()时,Vptr Table具有派生类foo()的地址,但是在派生类中是私有的...所以它怎么被调用.
我了解运行时多态性,并且我也了解访问说明符在编译时有效,而虚拟概念在运行时有效.这样就不会有编译器错误.
我的问题是:这是一个漏洞,通过它我们可以调用Derived类的私有方法?或预期会以这种方式表现. 对此行为有任何好的解释.
非常感谢.
代码:
class A
{
public:
virtual void foo()
{
std::cout << "In A";
}
};
class B:public A
{
private:
void foo()
{
std::cout << "In B ??? Its Private Method :-( ";
}
};
int main()
{
A* ptr = new B();
ptr->foo();
return 0;
}
这是私有方法,但是由于它是虚拟的-可以调用.
n3690 11.5/1
虚拟函数的访问规则(第11条)由其声明确定,不受以下内容的影响 稍后会覆盖该功能的规则.
为什么呢?自
n3690 11.5/2
通常是未知的(在上面的示例中为D).在调用点使用用于表示对象的表达式类型检查访问. 成员函数被调用(在上例中为B *). 对类中的成员函数的访问
I have a Base class pointer pointing to derived class object. The method foo() is public in base class but private in derived class. Base class foo() is virtual. So when i call foo() from Base class pointer, Vptr Table has the address of derived class foo(), BUT its private in Derived class ...so how is it getting called.??
I understand Run time polymorphism and i also understand that the Access specifiers work for compile time and Virtual concept works at run time. So there shall be No Compiler error.
My question is : Is this is a loop hole through which we can call private methods of Derived class ? or Its expected to behave this way. Any good Explanation for this behavior.
Thanks a lot in advance.
CODE :
class A
{
public:
virtual void foo()
{
std::cout << "In A";
}
};
class B:public A
{
private:
void foo()
{
std::cout << "In B ??? Its Private Method :-( ";
}
};
int main()
{
A* ptr = new B();
ptr->foo();
return 0;
}
It's private method, but since it's virtual - it can be called.
n3690 11.5/1
The access rules (Clause 11) for a virtual function are determined by its declaration and are not affected by the rules for a function that later overrides it.
Why this? Since
n3690 11.5/2
Access is checked at the call point using the type of the expression used to denote the object for which the member function is called (B* in the example above). The access of the member function in the class in which it was defined (D in the example above) is in general not known.
这篇关于派生类Private方法被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!