Silicomancer Silicomancer - 1 year ago 87
C++ Question

Can't call virtual protected method in derived class

The following code does not compile in GCC 4.9.1:

class A
virtual void f() {}


class B : public A
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?

Answer Source
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!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download