0

I have a base class A and a few derived classes B, C and D, that all have a method DoSomething(), which is virtual in the base class method (it's implemented in all sub classes as well as in the base class).

I have a problem, that the derived class B uses the method from the base class A. This may be the result of bad design, but I do not see the problem as the implementation is pretty straight forward.

An object of class B that is created in the following

A* a = new B();

If I call the method DoSomething() for this object, the method of the base class is used:

a->DoSomething(); //Results in Base class method being called.

But I expect/want that the method of class B is used. Can you tell me what's wrong?

Christophe
  • 68,716
  • 7
  • 72
  • 138
Xa Na
  • 31
  • 1
  • 7

2 Answers2

4

According to the symptoms that you describe:

  • either you have forgotten the virtual keyword in the base class member definition.
  • or you have a subtle difference in you signature in the derived class.

The way forward would be to indicate in the derived class that the function is an override:

class A { 
   ...
   virtual void DoSometing(); 
}; 
class D : public A {
   ...
   void DoSomething() override; 
};

In this case, in case of mismatch you'll get a clear compiler error message.

Christophe
  • 68,716
  • 7
  • 72
  • 138
0

The following example implements what you asked for.

#include <iostream>

class A
{
    public:
    virtual void DoSomething()
    {
            std::cout << "A::DoSomething" << std::endl;
    }
};

class B : public A
{
    public:
    virtual void DoSomething()
    {
            std::cout << "B::DoSomething" << std::endl;
    }
};

int main(int argc, char **argv)
{
    A *a = new B();
    a->DoSomething();
    delete(a);

    return 0;
 }

Output:

B::DoSomething
Francesco Argese
  • 626
  • 4
  • 11