views:

37

answers:

1

Hello,

I would like to understand why when I call protected method, declared and implemented in base class, from derived class via pointer to base class I get compilation error (C2248) and when I call it from derived class via pointer to derived class instance, compilation pass.

I understand it is part of the language but I want to understand why

My explanation is that when I call a protected member of base class via pointer to base class in derived class, compilation fails because the inheritance of base class can be protected or private but when I call it via pointer to derived class in a derived class it o.k because it is part of the class. Is that right?

e.g.

class Base 

{

protected:

   virtual void func() {}

}

class Derived : public Base

{

public:

   virtual void myMethod()

   {

      Base* pBase = new Base;

      pBase->func();          -> compilation error (C2248)

      Derived* pDerived = new Derived;

      pDerived->func();       -> O.K

    }
}
+1  A: 

The failing line is not compilable because you are accessing an instance of Base - only public methods can be accessed this way. If you do this in myMethod():

Base::func();

it should compile because now we are accessing the inherited method for this. Kind of weird to have pDerived::myMethod() call the Derived constructor?

Steve Townsend
The fact that I cannot access a protected method is understood the question is why when I call the same method but via an instance of pDerived, it compiles ?
David
@David - this works because you are calling the instance from within Derived::myMethod() in a another instance of Derived. All instances of Derived have the same access to any other instance's methods, as if they were their own. If myMethod were a global function, or a member of a different class (not 'Derived'), then this would fail just the same as it does for the call from Derived to Base.
Steve Townsend
Thank you for the help!!!
David