virtual function

can anyone explain the result of this program??? how the private function called

using namespace std;

class Base{

virtual void show() { cout << "Base function \n"; }

class Derived : public Base{

void show() { cout << "Derived function\n"; }

int main()

Base * pb;
Derived d;

pb = &d;


return 0;

Derived function
closed account (zb0S216C)
You can't call the overloaded "Derived::show( )" because you've made it private. However, you can still call "Base::show( )" from "Derived":

int main( )
    Dervied new_d;
    new_d.::Base::show( );

yes i know it but here when I write

pb-> show();

"Derived::show( )" has been called, which is private

I think this code compiles because it evaluates at run-time
Last edited on
closed account (zb0S216C)
Regardless of the access-level, "Base" is allowed to access operators, data members, and member functions that were derived from it. In your case "show( )" is derived from "Base", which means "Base" is allowed to access "show( )" of "Derived". This does not change with overloading.

Last edited on
You can't call the overloaded "Derived::show( )"

I just want to clarify - CV qualifiers would constitute overloaded, however, in this case, the access specifier private/public/protected does not overload the function, it is overridden. The fact that the derived function is called shows that this is overridden, because the overload would not even be visible to the base pointer.

The level of access is used for the object in which it is invoked, here the use of dynamic binding by a pointer to a base class, all access to an object pointed to by this pointer is is based off the base class.

closed account (zb0S216C)
@clanmjc: I don't know where you got the idea: "the access specifier private/public/protected does not overload the function". I full well that the level of access doe not override a function. I'm just saying that "Derived::show( )" cannot be called because it's private.

I was speaking to the OP, clarifying what you had said... because you said overload and not override.
You can't call the overloaded "Derived::show( )"
Because that function is not overloaded, it is overridden. The OP was just asking, why did the result of calling the function show() give him the "Derived" implementation. I was just clarifying exactly what happened and why it happened. His expected results, based on his question, was to get the base call or that it should not compile.

If that function was overloaded, it wouldn't matter if it was public or private, a base class pointer to a derived object would never even see the overload, ever.

The short program he posted, works, the call to virtual show from base class pointer calls the Derived::show implementation. The question was how/why this happened because show is private in Derived.
Last edited on
Topic archived. No new replies allowed.