tags:

views:

100

answers:

2
class base {  
    public: 
        int foo();  
        int foo(int a);  
        int foo(char* b);    
        int doSomething(int);    
 }

 class derived : public base
  { 
  public: 
     int doSomething(int b); 
  }

 int derived::doSomething( int b) 
   {
     base::doSomething(b);  
       //Make Something else 
   }

 int main() 
 { 
     derived d= new derived();  
     d->foo();
 }

now in the foo method (any of them) i want to call the more specific doSomething. if i instance a derived class i want the doSomething of the derived class, and if i instance a base class i want the doSomething of the base class, in spite of i'm calling from the foo method implemented in the base class.

int base::foo()
{
 //do something
 makeSomething(5);
}
+3  A: 

In your base class, make the doSOmething method virtual

public:

virtual int doSomething(int);

Then you can:

Base* deriv = new Derived();

Base* base  = new Base();

deriv->doSomething();
base->doSomething();

And rejoy

Tom
+2  A: 

That is what virtual functions are for:

struct A {
    virtual ~A() {}
    virtual void f() {}
};

struct B : A {
    void f() {}
};

// ...
A* a = new A;
A* b = new B;
a->f(); // calls A::f
b->f(); // calls B::f

The C++ FAQ lite covers some details, but can't substitute a good introductory book.

Georg Fritzsche
thanks for that's links
Luciano Lorenti