Overloading the C ++ function for classes

advertisements

I have 3 classes

class A {
//...
}

class B : public A {
//...
}

And a class C:

#include "A.h"
#include "B.h"

class C
{
   void method(A anObjOfA);
   void method(B anObjOfB);
}

Now if I do

B* ptr = new B();
A* ptrToB = ptr;
c.method(*ptrToB);

It calls the method for Objects of type A, not the inherited actual type B.. How can I make sure the right function for the object deepest in the inheritence-tree is called, without actually knowing it's type at compile-time?

PS: I'm sure this is a noob question, for the life of me I can't find any results on this here, as everyone is busy understanding the "virtual" keyword, which is perfectly clear to me but is not the issue here.


Because resolving a function overload is done at compile-time. When you call the function it only sees the A part of the pointer, even though it could point to a B.

Perhaps what you want is the following:

class A
{
public:
    virtual void DoWorkInC()
    {
        cout << "A's work";
    }
    virtual ~A() {}
};

class B : public A
{
public:
    virtual void DoWorkInC()
    {
        cout << "B's work";
    }
};

class C
{
   void method(A& a)
   {
        a.DoWorkInC();
   }
}