0
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);
}
Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
Luciano Lorenti
  • 601
  • 2
  • 11
  • 22

3 Answers3

3

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 enjoy!

mauris
  • 42,982
  • 15
  • 99
  • 131
Tom
  • 43,810
  • 29
  • 138
  • 169
2

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.

Community
  • 1
  • 1
Georg Fritzsche
  • 97,545
  • 26
  • 194
  • 236
0

I would propose this example as to illustrate difference between use of virtual or non-use

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

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

A* a = new A;
A* b = new B;
a->f(); // calls A::f
b->f(); // calls B::f
b->g(); // calls A::g
kiriloff
  • 25,609
  • 37
  • 148
  • 229