N
N
Nikita Savinykh2018-02-01 14:39:32
OOP
Nikita Savinykh, 2018-02-01 14:39:32

How to make different implementation of the same class function in C++?

Suppose we have a certain model, and let's say we wanted an event to fire on click. Approximately such a class will allow us to process a click (we will omit the implementation):

Class Model{
Model();

public:
void click();
}

However, by defining this function, we cannot force different models to behave differently.
The essence of the question is precisely that for each instance of the Model class, the click () function is performed differently. And if it is still possible, by redefining this function, to change the number and types of arguments, then it will be generally good. Thanks in advance to everyone for answers or suggestions to google for keywords (I would be extremely grateful if they were voiced)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Mercury13, 2018-02-01
@Ukio_G

Transfer user functionality to another place - the so-called "listener".

using EvClick = void (*)();

Class Model{
public:
  void click() { if (fOnClick) fOnClick(); }
  void setOnClick(EvClick x) { fOnClick = x; }
private:
  EvClick fOnClick = nullptr;
}

There are similar listeners in any visual window library: VCL, Qt. In VCL it is, except for the properties entered in the syntax. Qt uses signal slots for this.
Establish the transfer of any data to this function - the “command” template.
class ClickEvent {
public:
  int x, y;
  virtual ~ClickEvent();
}

using EvClick = void (*)(ClickEvent&);

A
Alexander, 2018-02-01
@alexr64

Not exactly C++, but you get the idea

D
devalone, 2018-02-01
@devalone

Either store a function pointer en.cppreference.com/w/cpp/utility/functional/function (well, or raw), or make the base function virtual, or both, like this.

class Base {
public:
  virtual ~Base() {}
  virtual doIt()
  {
    if (callback)
      callback();
  }
private:
  std::function<void()> callback;

And in the inherited one, it will be possible to override doIt and it will do something else.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question