[英]Derived class Private method is getting called
I have a Base class pointer pointing to derived class object. 我有一个指向派生类对象的基类指针。 The method foo() is public in base class but private in derived class. 方法foo()在基类中是公共的,但在派生类中是私有的。 Base class foo() is virtual. 基类foo()是虚拟的。 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.?? 因此,当我从基类指针调用foo()时,Vptr Table具有派生类foo()的地址,但它在派生类中是私有的...那么它怎么被调用。
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 ? 我的问题是:这是一个循环孔,通过它我们可以调用Derived类的私有方法? 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 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. 虚拟函数的访问规则(第11条) 由其声明确定,并且不受后来覆盖该函数的函数规则的影响。
Why this? 为什么这个? Since 以来
n3690 11.5/2 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). 在调用点使用用于表示为其调用成员函数的对象的表达式的类型(在上例中为B *)检查访问。 The access of the member function in the class in which it was defined (D in the example above) is in general not known. 通常不知道在定义成员函数的类中访问成员函数的情况(上述示例中的D)。
Access level is a compile-time concept. 访问级别是一个编译时概念。 The runtime doesn't know if a method was declared private
or public
. 运行时不知道方法是被声明为private
还是public
。 Those are there for your convenience. 这些是为了您的方便。
This is actually a good coding standard - a virtual
method should be ideally public
in the base class and private
or protected
in derived classes. 这实际上是一个很好的编码标准- virtual
方法最好在基类中是public
,而在private
类中应该是private
或protected
。 This will force the caller to use the interfaces rather than the actual types (of course, this isn't always practical, but a good thing to take into account). 这将迫使调用者使用接口,而不是实际的类型(当然,这并不总是实用的,但要考虑到这是一件好事)。
The concrete type is abstracted away in your case, as it should be. 具体类型应按您的情况抽象出来。 The base method is declared public
and you're calling it through a pointer to a base, so it's allowed. base方法被声明为public
并且您是通过指向base的指针来调用它的,因此允许它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.