Home     |     .Net Programming    |     cSharp Home    |     Sql Server Home    |     Javascript / Client Side Development     |     Ajax Programming

Ruby on Rails Development     |     Perl Programming     |     C Programming Language     |     C++ Programming     |     IT Jobs

Python Programming Language     |     Laptop Suggestions?    |     TCL Scripting     |     Fortran Programming     |     Scheme Programming Language


 
 
Cervo Technologies
The Right Source to Outsource

MS Dynamics CRM 3.0

C++ Programming

Why polymorph fails when virtual function is decleared private in base class and public in derived class?


I've got the following code:

#include <iostream>

class Base{
private:
        virtual void f(int) { std::cout << "f in Base" << std::endl; }

};

class Derived : public Base{
public:
        virtual void f(int) { std::cout << "f in Derived" << std::endl; }

};

int main(void)
{
        Base base;
        Derived derived;

        Base* p = &derived;
        p->f(2);

        return 1;

}

In base class f is decleared as private member function, and the
compiler complains that pointer p couldn't access private member in
base. It's clear that polymorph fails here. Why does it happen? Thanks
for help.
* Fred:

Right.

> It's clear that polymorph fails here.

Polymorphism doesn't fail.

> Why does it happen?

The statically known type (the type known at compile time) is Base.  And
in Base, that member function is private.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?

The dynamic type of the object is only tested at the last step
in the selection of the virtual function.   Everything else uses
the static type.  The call is done roughly as follows:

1.   The name of the function is looked up in the calling scope.
2.   Overloads for that name are checked to find the best match.
3.   The protection for that overload is checked.
4.   Then IF the function is virtual, the final overriding function
     is called

The difference between static and dynamic type only comes into play
at step 4.

Add to del.icio.us | Digg this | Stumble it | Powered by Megasolutions Inc