-1

I'm having this issue with inheritance I just cannot wrap my head around. I have three classes, with a parental relationship between them. All of them has the function calcForces().

class Object {
public:
    virtual void calcForces();
};


class Boat : public Object {
public:
    virtual void calcForces();
};


class Sailboat : public Boat {
public:
    void calcForces(Wind wind);
};

Now my problem is that I I have a object created as a Sailboat (and saved it in an Object-pointer), but when I call calcForces() I end up inside Boat::calcForces(), not Sailboat::calcForces(). What am I doing wrong?

Here is my call to the function:

(*this->object_ptr_arr[i]).calcForces();    //'object_ptr_arr' is of type 'Object**'
Hoxbot
  • 105
  • 9

3 Answers3

11

The declarations of the overrides must match. Your declaration for Sailboat::calcForces takes a different parameter (a Wind instance) and therefore is not an override.

As commented by @stefaanv and @skypjack you can avoid this issue by embracing the use of the override function specifier, which would've caught the error at compile time.

acraig5075
  • 10,588
  • 3
  • 31
  • 50
2

If you want an calcForces() method in your sailboat you should add it there. At the moment you only have a calcForces(Wind wind) method in your sailboat (and the calcForces() that is inherited from Boat)

So when you are calling calcForces without a parameter it will end up in the inherited method. To fix this either add it in Sailboat like described above or call it with an variable of type Wind

Rafiwui
  • 544
  • 6
  • 19
2

Suggestion - boats and sailboats exist in an environment. The boat knows how it is affected by the environment.

class Environment
{
public:
  Wind wind;
};

class Object {
public:
    virtual void calcForces(Environment const&);
};


class Boat : public Object {
public:
    virtual void calcForces(Environment const& env); // can ignore the wind
};


class Sailboat : public Boat {
public:
    void calcForces(Environment const& env) override;  // will use env.wind in calculation
};

Now you are able to modify the environment and ask all objects in the environment to calculate their forces. Whether they're boats, sailboats or dolphins.

Richard Hodges
  • 68,278
  • 7
  • 90
  • 142
  • Very good suggestion and definitely preferable because of the object-orientated approach. But that isn't very helpful if he is facing similiar problems in the future because it doesn't describes what he was doing wrong. – Rafiwui Oct 16 '17 at 12:44