Click here to Skip to main content
15,887,485 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi everyone i have one question is my mind

This program worked
-----------------------------------------
#include<iostream>
using namespace std;
//declaring base class
class Base {
public:
    virtual int fun(int i) { cout << "Base::fun(int i) called"; }
};
//Declaring Derived class
class Derived: public Base {
private:
    int fun(int x)   { cout << "Derived::fun(int x) called"; }
};
int main()
{
    Base *ptr = new Derived;
    ptr->fun(10);
    return 0;
}

//It worked and gave output as :
Derived::fun(int x) called

But the below program didn't worked, don't know why
-------------------------------------------------
#include<iostream>
using namespace std;
//Declaring base class
class Base {
private:
    virtual int fun(int i) { cout << "Base::fun(int i) called"; }
};
//Declaring Derived class
class Derived: public Base {
public:
    int fun(int x)   { cout << "Derived::fun(int x) called"; }
};
int main()
{
    Base *ptr = new Derived;
    ptr->fun(10);
    return 0;
}


What I have tried:

I have learnt virtual functions but got confused in above two programs working
Posted
Updated 28-Aug-17 21:30pm

1 solution

The second version will generate a compiler error. The compiler sees an access to Base::fun() which is denied because that is private.

In the first version it is allowed because the Base::fun() is public. Because the function is virtual, the compiler will not generate code to call the function code directly but to use the vtable of the object (dynamic dispatch). Because the object is of type Derived, the vtable will point to Derived::fun() at run-time and that is called. The vtable does not know about the accessibility of the dispatched function and so it works even when the effectively called function is declared as private.
 
Share this answer
 
Comments
CPallini 29-Aug-17 3:47am    
5.
Member 11692369 30-Aug-17 0:49am    
What i think is that the object is created is of Derived type, so basically it should called Dervied::fun(), and it is public too.
Please help me understanding if i am wrong.
Member 11692369 30-Aug-17 1:39am    
Now i understood after i learnt Vtable and Vptr,
Thanks
Jochen Arndt 30-Aug-17 3:08am    
Fine that you understand it and thank you for accepting my solution.

It is a complex topic. But you can avoid such problems when follewing this rule:
Don't change the accessibility mode of virtual functions in derived classes.
If you have to do it for a very special reason, document that in your code.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900