Consider following code:
class A {
public:
virtual void f() const = 0;
void callf() const { f(); }
};
class B : public A {
virtual void f() const { }
};
int main()
{
B x;
x.callf();
return 0;
}
Class B
derives from the abstract base class A
, but "hides" the implemented method f()
as private member. Still, the inherited member callf()
is able to call f()
, which was public in the base class. The code compiles with no warning on g++ 10.1.0 and clang++ 11.1.0.
Is this a legal code, ie, does the inherited callf()
correctly see the private member f()
?
Alternatively, would it be possible for the derived class B
to implement the purely virtual methods of the base class, such that they can only be called by B
(and friends)?
Is this a legal code, ie, does the inherited callf() correctly see the private member f()?
Yes, it is legal code. From the compiler's point-of-view, the callf
function is referencing the f
function of its own class; the fact that that is a virtual function does not affect the scope (or accessibility) – only the implementation, which will be in the form of a call to a v-table entry. That v-table entry will be correctly interpreted at run time, when it is called via the derived class.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.