16

In the example below, why is B::f() called even though it is private?

I know this fact that : Access is checked at the call point using the type of the expression used to denote the object for which the member function is called.

#include <iostream>

class A {
public:
  virtual void f() { std::cout << "virtual_function"; }
};

class B : public A {
private:
  void f() { std::cout << "private_function"; }
};

void C(A &g) { g.f(); }

int main() {
  B b;
  C(b);
}
quamrana
  • 37,849
  • 12
  • 53
  • 71
test program
  • 281
  • 1
  • 8
  • 2
    Because it is public in A, presumably and due to the fact that A is a parent and you are using it from an A object it doesn't bother checking the scope on the child, it is just overridden by the fact that it is public in A. Just my thoughts. – tom Jan 22 '15 at 20:02
  • 3
    What you've stated explains it - the static type of `g` in `C` is `A&`, and `f()` is a public member function of `A`. That's all access control cares about. Change `C()`'s parameter type to `B&` and your code will fail to compile. – Praetorian Jan 22 '15 at 20:03

3 Answers3

25

Because the standard says so:

[C++11: 11.5/1]: The access rules (Clause 11) for a virtual function are determined by its declaration and are not affected by the rules for a function that later overrides it. [ Example:

class B {
public:
  virtual int f();
};
class D : public B {
private:
  int f();
};
void f() {
  D d;
  B* pb = &d;
  D* pd = &d;
  pb->f();       // OK: B::f() is public,
                 // D::f() is invoked
  pd->f();       // error: D::f() is private
}

—end example ]

The example is the same as yours, lol.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
6

private functions can override public virtual functions from a base class. Accessability is, in a fact, completely ignored when determining whether a function overrides another, so even in

// Redundant private for clarity:
class A { private: virtual void foo(); };
class B : A { public: void foo(); };

B::foo overrides A::foo.

Columbo
  • 60,038
  • 8
  • 155
  • 203
4

During compile time C++ compiler verifies accessibility of functions and methods based on their type. In function C variable g is of type A (checked during compilation of the code), in which method f is declared as public.

Take a look at this link

Igor Popov
  • 2,588
  • 17
  • 20