Mseb
Mseb

Reputation: 3

C++: calling same function of multiple classes

I am looking for a way to call the same function in multiple classes without having to make separate functions for each class.

Example:

class A{
public:
void update();
}

class B{
public:
void update();
}

Now i want to create a function that can take both class A or class B and call the update() function. I have been looking for a solution on stack overflow / google but can't find anything. I was looking at templates but was not able to find anything that works. In my project I have around five or six classes each having a update() function needing to be called every frame. I am using a common base class but the update() function needs to be located in the derived class. I had the same issue at my last project and can't figure this out.

Upvotes: 0

Views: 1616

Answers (1)

milbrandt
milbrandt

Reputation: 1486

why can't you define an pure virtual update method in your base class? (Or even a second base class/Interface which only has this virtual method.)

class IUpdate
{
    public:
    virtual void update() = 0;
}

class A : public IUpdate
{
    public:
    void update();
}

And the same for class B.

Upvotes: 2

Related Questions