'virtual function doubts c++
Virtual function d() in the base class A is overidden by a private method in derived class B. When d() is invoked on an instance of B from outside, via a pointer of type A *, it is B::d() that runs, even though it is private to B.
Why does this happen? Shouldn't it be impossible for code outside B to invoke B's private methods?
Demo
#include<iostream>
using namespace std;
class A {
public:
virtual void d(){
cout<<" gfgd ";
}
};
class B :
public A
{
private:
void d(){
cout<<"hytyhtht";
}
};
int main() {
A *a1;
B b;
a1=&b;
a1->d();
return 0;
}
Output:
hytyhtht
Solution 1:[1]
The public/protected/private access-rules are enforced at compile-time, not at run-time, which means that they have to rely on logic that the compiler can enforce at compile-time.
In particular, the compiler knows that you are calling the d() method using a A* pointer, and that class A has declared virtual void d() to be a public method, so that means it's okay to call the method.
In general the compiler can't know at compile-time that your pointer is really pointing to a B object, so even if it wanted to it wouldn't be able to flag the call as a compile-time error. (Well, maybe in your particular example it could, but in many cases the compiler doesn't know what the type of the pointer-to object will be, it only knows the type of the pointer)
For example:
// in someotherfile.cpp
void MyFunction(A * a)
{
a->d(); // should this compile, or not?
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jeremy Friesner |
