Overrding virtual methods

Discussion in 'C++' started by kilombo, Sep 2, 2009.

  1. kilombo

    kilombo New Member

    Joined:
    Aug 31, 2009
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    Hi,

    I've defined an abstract class IBase with a single method

    virtual bool foo(){ printf(" IBase \n"); }


    I've also defined a derived class TestDerived:IBase that overrides this method

    bool foo(){ printf(" TestDerived \n");}


    Finally I've a static lib with a function to use a IBase class

    bool doSomething(IBase * foo);

    implemented inside the library :

    bool doSomething(IBase * foo){ foo->foo(); }

    And this is the main program :
    #include "mystaticlib.h"

    int main(){
    IBase * ptr = new TestDerived();
    ptr->foo();
    doSomething(ptr);
    }
    I was especting an output like :

    TestDerived
    TestDerived


    But the output is

    TestDerived
    IBase

    Why inside the lib, the ptr is accessing to the method of the base?


    Thanks in advance.
     
  2. Mridula

    Mridula New Member

    Joined:
    Mar 5, 2008
    Messages:
    316
    Likes Received:
    19
    Trophy Points:
    0
    Occupation:
    S/w proffessional
    Location:
    Bangalore
    Hi,

    Here is the program you have explained below and it's output too

    Code:
    #include<iostream.h>
    
    class Base
    {
      public:
        virtual bool foo()
        {
          cout<<"Base::foo"<<endl;
        }
    };
      
    class Derived: public Base
    {
      public:
        bool foo()
        {
          cout<<"Derived::foo"<<endl;
        }
    };
    
    bool doSomething(Base * foo)
    { 
      foo->foo(); 
    }
    
    int main()
    {
      Base *bptr = new Derived();
      bptr->foo();
      doSomething(bptr);
      
      return(0);
    }
    
    
    output:

    Derived::foo
    Derived::foo


    You must get the output as you were expecting. I think, you have made some mistake to get the output as

    Derived::foo
    Base::foo


    So, double check your code.
     
    Last edited by a moderator: Sep 2, 2009
  3. kilombo

    kilombo New Member

    Joined:
    Aug 31, 2009
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    I double check it ..... and you were right. :) The output is ok.

    Thanks for all.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice