Access control of derived class

Z

zs0723

#include <iostream>
using namespace std;

class A
{
public:
virtual void foo(){ cout<<"A::foo"<<endl;}
};


class B:public A
{
protected:
virtual void foo(){ cout<<"B::foo"<<endl;}
};


class C:public A
{
private:
virtual void foo(){ cout<<"C::foo"<<endl;}
};

int main()
{
A *p = new B;
p->foo();

A * q =new C;
q->foo();

}

My question is why p->foo() can work , I think foo() method in class B
is protected ,
the external client have no right to access it.
 
N

Neelesh

#include <iostream>
using namespace std;

class A
{
  public:
        virtual void foo(){ cout<<"A::foo"<<endl;}

};

class B:public A
{
  protected:
        virtual void foo(){ cout<<"B::foo"<<endl;}
 };

class C:public A
{
  private:
        virtual void foo(){ cout<<"C::foo"<<endl;}
 };

int main()
{
   A *p = new B;
   p->foo();

   A * q =new C;
   q->foo();

}

My question is why p->foo() can work , I think foo() method in class B
is protected ,
the external client have no right to access it.

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. Thus, when A::foo() is declared as public, it
doesnot affect the accessibilty of A::foo() even when class B declares
B::foo as private. In addition, the compiler checks for access at the
call point using the static type of the expresion used to denote the
object. In the current example, the static type of q in q->foo() is A*
and static type of p in p->foo() is also A*. since A::foo is public,
the compiler has no problem here.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top