1

I'm trying to override virtual methods of super class in the bottom most derive class in multilevel inheritance scenarios. I have two cases here-

Case 1: Sub class(bottom most) overriden function is protected

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

class B: public A
{
public:
};

class C: public B
{
protected:
    void f1()
    {
        cout<<"C::f1() called"<<endl;
    }


};
int main()
{
    A* a= new C;
    a->f1();
  
}

This is working fine even when we calling a protected function C::f1() from main(). But the second case is giving me compilation issue, as i'm making A::f1() as protected.

Case 2:Super class virtual function is protected

class A
{
protected:
    virtual void f1()
    {
        cout<<"A::f1() called"<<endl;
    }
         
};

class B: public A
{
public:
};

class C: public B
{
public:
    void f1()
    {
        cout<<"C::f1() called"<<endl;
    }


};
int main()
{
    A* a= new C;
    a->f1();
  
}

Please help me why in second case its compilation error while the case:1 f1() is called fine?

amateur17
  • 9
  • 3
  • The method is protected so you cannot access it from outside – RoQuOTriX Sep 28 '21 at 12:28
  • 1
    seems like you are thinking too complicated. Forget about all the inheritance structure, then `a` is a pointer to an `A` and `A::f1` is `protected` thats all that matters here. You cannot call a protected method from outside – 463035818_is_not_an_ai Sep 28 '21 at 12:30
  • @463035818_is_not_a_number true , i cannot call a protected member of a class from main() . But how do i'm able to call the C::f1() from main using A* pointer from main, as C::f1() is protected too. Overall my confusion lies as the access control rules need to be applied on Base* pointer or the actual object it is pointing to ? in our case (Base* b= new Derive; ) . Please help – amateur17 Sep 28 '21 at 14:42

0 Answers0