Why is base inaccessible to deriv inside deriv? The program compiles with class deriv : public base.
#include <cstdio>
class base
{
};
class deriv : base
{
public:
void f(deriv, int){printf("deriv::f(deriv, int)\n");}
void f(base){printf("deriv::f(base)\n");}
};
int main()
{
deriv d;
d.f(d);
}
17: error: ‘base’ is an inaccessible base of ‘deriv’
17: error: initializing argument 1 of ‘void deriv::f(base)’
Because two people got it wrong already, I will ask in bold: why does base need to be publicly inherited? It is accessed from within deriv only.
You seem to be incorrectly assuming that conversion from
derivtobasewhen callingderiv::f(base)occurs “insidederiv” and thus has to be accessible. This is not the case. When you call a function, all conversions necessary for initializing function’s arguments occur in the caller’s context. They are not “insidederive“. They happen in the “outside world”. And in your case the “outside world” has no access toderiv-to-baseconversion.In your specific case it is
mainthat is trying to convertderivtobase. Andmaincannot do it since it has no access to the private base ofderiv. Just to experiment you can declareint main()as a friend ofderivand the code will compile.