4
votes

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

1 Answers

3
votes

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?