File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ // <Selected Topic in C++> Topic 13 Function Pointers
2
+ #include < iostream>
3
+ #include < vector>
4
+ using namespace std ;
5
+ class BaseClass {
6
+ public:
7
+ int objId;
8
+ BaseClass (int objId): objId(objId) {}
9
+ virtual void callBackFun () {
10
+ cout << " BaseClass callBackFunc " << objId << endl;
11
+ }
12
+ };
13
+
14
+ class DerivedClass : public BaseClass {
15
+ public:
16
+ DerivedClass (int objId) : BaseClass(objId) {}
17
+ virtual void callBackFun () {
18
+ cout << " DerivedClass callBackFunc " << objId << endl;
19
+ }
20
+ };
21
+
22
+ void commonCallbackFunc (BaseClass *obj, void (BaseClass::*callbackFuncPtr)()) {
23
+ (obj->*callbackFuncPtr)();
24
+ }
25
+
26
+ int main (int argc, char ** argv) {
27
+ // vector<BaseClass*> collector = {BaseClass(1), DerivedClass(2)}; // will call vector<T> allocator to allocate memory on heap??
28
+ vector<BaseClass*> objs = {new BaseClass (1 ), new DerivedClass (2 )};
29
+ void (BaseClass::*callbackFuncPtr)() = &BaseClass::callBackFun;
30
+ for (auto ptr : objs) {
31
+ commonCallbackFunc (ptr, callbackFuncPtr);
32
+ delete ptr;
33
+ }
34
+ return 0 ;
35
+ }
You can’t perform that action at this time.
0 commit comments