-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcallbacks.cpp
More file actions
73 lines (58 loc) · 1.75 KB
/
callbacks.cpp
File metadata and controls
73 lines (58 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
//
// Created by Mayank Parasar on 2019-12-03.
//
/*Implementing the callback using an interface-class*/
#include <iostream>
using namespace std;
class CallbackInterface { // this is an abstract class
public:
// the prefix 'cbi' to prevent naming clashes.
virtual int cbi_CallbackFucntion(int)=0;
};
// The class that wants to be called back from the CallbackInterface
// and implementa the callback funciton
class Callee2 : public CallbackInterface {
public:
// The callback function that caller will call.
int cbi_CallbackFucntion(int i) {
cout << "Callee::cbi_CallbackFunction() inside callback" << endl;
return 3 * i;
}
};
// The class that wants to be called back from the CallbackInterface
// and implementa the callback funciton
class Callee : public CallbackInterface {
public:
// The callback function that caller will call.
int cbi_CallbackFucntion(int i) {
cout << "Callee::cbi_CallbackFunction() inside callback" << endl;
return 2 * i;
}
};
class Caller {
public:
// Clients can connect theit callback with this
void connectCallback(CallbackInterface *cb) {
m_cb = cb;
}
// Test the callback to make sure it works.
void test() {
cout << "Caller::test() calling callback..." << endl;
int i = m_cb->cbi_CallbackFucntion(10);
cout << "Result (20): " << i << endl;
}
private:
// The callback provided by the client via connectCallback(
CallbackInterface *m_cb;
};
int main() {
// a pointer to callee can be passes to a function or object
// that will call it back
Caller caller;
Callee callee;
// Connect the callback
caller.connectCallback(&callee); // binding
// Test the callback
caller.test();
return 0;
}