Virtual function behaviour

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Rahul K

    Virtual function behaviour

    Hi all

    I tried running the following code:

    #include<iostre am.h>

    class Base
    {
    public:
    virtual void func()
    {
    cout << "Inside Base Class" << endl;
    }
    };

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

    void main()
    {
    Derived d;
    Base *bptr;
    bptr = &d;
    bptr->func();
    }

    As per my knowledge, I thought that since the derived class does not
    publicly override the virtual function of base class, the func() of
    base class will be called. Also, since the derived class defines func()
    in private, there is no question of it getting called from main.

    However to my surprise, the output was :
    Inside Derived

    Can anybody explain me this behaviour that how a private function was
    called. Does it means that overriding a virtual function in derived
    class either in private or public will lead to run time polymorphism.

  • Sunil Varma

    #2
    Re: Virtual function behaviour


    Rahul K wrote:[color=blue]
    > Hi all
    >
    > I tried running the following code:
    >
    > #include<iostre am.h>
    >
    > class Base
    > {
    > public:
    > virtual void func()
    > {
    > cout << "Inside Base Class" << endl;
    > }
    > };
    >
    > class Derived:public Base
    > {
    > private:
    > void func()
    > {
    > cout << "Inside Derived" << endl;
    > }
    > };
    >
    > void main()
    > {
    > Derived d;
    > Base *bptr;
    > bptr = &d;
    > bptr->func();
    > }
    >
    > As per my knowledge, I thought that since the derived class does not
    > publicly override the virtual function of base class, the func() of
    > base class will be called. Also, since the derived class defines func()
    > in private, there is no question of it getting called from main.
    >
    > However to my surprise, the output was :
    > Inside Derived
    >
    > Can anybody explain me this behaviour that how a private function was
    > called. Does it means that overriding a virtual function in derived
    > class either in private or public will lead to run time polymorphism.[/color]

    virtual functions assume the access level of the pointer or reference's
    class through which that funciton it is called.

    in your example in the base class the access level of the virtual
    function is public.
    you are making a call to the virtual funtion through the pointer of
    type base.
    so, you can call the virtual function in derived with access level
    public with base pointer.

    Comment

    Working...