How come I am able to access my private function

M

msalters

Nivvy schreef:
HI all,

I just wondered by seeing the o/p of the program. Let me know wt is the
reason.

class Base
{
public :
virtual void f1()
{
cout << "Base::f1() "<<endl;
}
};

class Derived : public Base
{
private:
void f1()
{
cout << "Derived::f1() "<<endl;
}
};

int main()
{
Base *bp = new Derived;
bp->f1();

return 0;
}


It ouputs the Derived private function.
What is the reason, whether this is like breaking OOPS.

The reason for this is that Derived implements not only its own
interface, but also the Base interface. In the Base interface,
f1 is public. That means anybody who use the Base interface can
get f1 - independent of the class implementing that interface.

In your case, Derived implements the Base interface for f1 and
main uses that interface. Both sides follow proper OO rules, so
the compiler doesn't stop you.

Now, the Derived interface doesn't offer f1. That may seem strange
but there is no OO requirement for that. A derived class may offer
additional interfaces which are not supersets of the Base interface.
(This is also what allows Multiple Inheritance - those interfaces
are also incompatible with Base ).

HTH,
Michiel Salters
 
R

Ron Natalie

Nivvy said:
It ouputs the Derived private function.
What is the reason, whether this is like breaking OOPS.
There's nothing broken. Access control is checked before the virtual
function overriding happens. You can generally view a member function
call as working this way:

1. The name is looked up. (In this case *bp is type Base, so Base::f1
is found).

2. Overloads for that name are checked. There is only one f1(void).

3. Then access control is checked. Base::f1(void) is public.

4. Then since Base::f1 is virtual, the dynamic type is checked for
overriding functions and Derived::f1 is executed.
 
M

Matthias Kaeppler

David said:
Does what it can do make sure things do not go wrong? No, I am afraid
Java doesn't do that. It would be nice, though.

You misunderstand me. I didn't mean Java makes sure that everything
works. it by far doesn't. With "Java does that" I was referring to Java
suppressing exactly the problem we're talking about, by checking the
function signature at compile time. So in this point, Java /does/ make
sure this thing can't go wrong (and that's perfectly fine!).
It's also not a performance penalty, since this check is done at compile
time.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,434
Messages
2,571,689
Members
48,796
Latest member
Greg L.

Latest Threads

Top