Search code examples
c++protectedvirtual-functions

Can't call virtual protected method in derived class


The following code does not compile in GCC 4.9.1:

class A
{
protected:
   virtual void f() {}

};

class B : public A
{
protected:
   virtual void f() override { A* a = new A; a->f(); }
};

I get the following:

header.h: In member function 'virtual void B::f()':
header.h:51:17: error: 'virtual void A::f()' is protected

I would have expected this to compile.

Why does it fail? Is there a better way than making f() public?


Solution

  • A* a = new A; a->f();
    

    IS the problem here: You cannot call f() from a since it is not public, and not accessible to B in the member function scope.


    It Works!