Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   Overrding virtual methods (http://www.go4expert.com/forums/overrding-virtual-methods-t19268/)

kilombo 2Sep2009 14:48

Overrding virtual methods
 
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.

Mridula 2Sep2009 15:41

Re: Overrding virtual methods
 
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.

kilombo 2Sep2009 16:02

Re: Overrding virtual methods
 
I double check it ..... and you were right. :) The output is ok.

Thanks for all.


All times are GMT +5.5. The time now is 23:44.