0
class Entity {
  public:
    virtual void applyCollisionBehaviorTo(Entity &entity) { }
    
    virtual void onCollision(Entity &entity) { }
};

class Ball : public Entity {
  public:
    void applyCollisionBehaviorTo(Entity entity) override {
      
    }

    void onCollision(Entity entity) override {
      entity.applyCollisionBehaviorTo(this); // error: no matching function for call to 'Entity::applyCollisionBehaviorTo(Ball*)'
    }
};

void setup() {
  // put your setup code here, to run once:

}

void loop() {
  // put your main code here, to run repeatedly:

}

I come from a C# background so I'm getting my head around C++ inheritance and polymorphism.

5
  • 1
    Because it has not been declared at that point. You only declare it later. Commented Feb 17, 2021 at 0:51
  • Also, the base classes shouldn't know about the derived ones! Commented Feb 17, 2021 at 0:53
  • You don't. It defeats the whole point using inheritance in the first place. Are you maybe trying to implement some kind of double dispatch? Commented Feb 17, 2021 at 0:53
  • In order to pass Ball by value you need to have a full definition of it prior to the use. But you can pass a pointer or reference to it using just a forward declaration. Commented Feb 17, 2021 at 1:02
  • I've updated the question to reflect more of what the problem is. Commented Feb 17, 2021 at 1:08

1 Answer 1

1

Your class Entity should be like this:

class Entity
{
 public:
   virtual void applyCollisionBehaviorTo(Entity &entity) = 0;    
   virtual void onCollision(Entity &collidingEntity) = 0;
};

You can't refer to object of Ball class inside Entity, in fact entities don't even know about the existence of balls.

OTOH balls "know" that they are entities

Sign up to request clarification or add additional context in comments.

5 Comments

Yeah, see I tried that but I get: no matching function for call to 'Entity::applyCollisionBehaviorTo(Ball*)' in the Ball class when passing this.
Because you must pass *this
this is a pointer. If you use a reference or a value, you must dereference it
Okay great, *this seemed to fix it on my end :) Thank you.
You're welcome, but keep in mind that you still have to match the methods signatures in Ball

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.