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);
}
Private: The class members declared as private can be accessed only by the functions inside the class. They are not allowed to be accessed directly by any object or function outside the class.
The definition of member functions can be inside or outside the definition of class. If the member function is defined inside the class definition it can be defined directly, but if its defined outside the class, then we have to use the scope resolution :: operator along with class name alng with function name.
We can call the private method of a class from another class in Java (which are defined using the private access modifier in Java). We can do this by changing the runtime behavior of the class by using some predefined methods of Java. For accessing private method of different class we will use Reflection API.
If a member function's definition is outside the class declaration, it is treated as an inline function only if it is explicitly declared as inline . In addition, the function name in the definition must be qualified with its class name using the scope-resolution operator ( :: ).
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With