virtual function in c++ and inheritance

#include <iostream>

using namespace std;
class a
{
public:

virtual void add()
{
cout<<"class in a ";
}
};
class b:public a
{
void add() // this is under the private label why this add invoke easely
{
cout<<"class in b";
}

};
int main()
{
a *p;
b n;
p=&n;
p->add();
return 0;
}
Because p is of type a* and a::add() is public.
> this is under the private label why this add invoke easely

Legalese: that is what the IS specifies:
The access rules for a virtual function are determined by its declaration and are not affected by the rules for a function that later overrides it.


Annotation:
C++ is compiled to native code using a separate compilation model.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
struct A { virtual ~A() ; virtual void foo() ; };

void bar( A& a ) // we can write (and compile) bar() before any derived class of A is written
{
      // the static (compile-time) type of a is 'reference to A'
      // look up is based on the static type

      a.foo() ; 

      // look up A, A::foo() is public, access is allowed
      // A::foo() is virtual, bind at run-time based on the dynamic type of the object
      // ergo, call most overridden foo()

      // however, when this code is compiled, we have no knowledge of 
      // which class has that most overridden foo(), or what the access rules 
      // are in that class. That class need not even exist when this code is compiled. 
}
@JLBorges i understand thanks
Topic archived. No new replies allowed.