Skip to content

Instantly share code, notes, and snippets.

@barenko
Created August 31, 2018 13:51
Show Gist options
  • Save barenko/b2c0bff36d80c036f9e140e9d56724fe to your computer and use it in GitHub Desktop.
Save barenko/b2c0bff36d80c036f9e140e9d56724fe to your computer and use it in GitHub Desktop.
Generic pointer to access subclass methods
class Super {
public:
void action(){ Print("Super");}
};
class A : public Super {
public:
void action(){ Print("A");}
};
class B : public Super {
public:
void action(){ Print("B");}
};
void action(){
Super* s = new Super();
A* a = new A();
B* b = new B();
Print("Using direct access with right pointer type");
s.action();
a.action();
b.action();
Super* arr[3];
arr[0] = s;
arr[1] = a;
arr[2] = b;
Print("Using indirect access with the generic pointer type");
for(int i=0;i<3;i++) arr[i].action();
}
/* OUTPUT
2018.08.31 10:37:40.994 2018.08.22 00:00:00 Using direct access with right pointer type
2018.08.31 10:37:40.994 2018.08.22 00:00:00 Super
2018.08.31 10:37:40.994 2018.08.22 00:00:00 A
2018.08.31 10:37:40.994 2018.08.22 00:00:00 B
2018.08.31 10:37:54.379 2018.08.22 00:00:00 Using indirect access with the generic pointer type
2018.08.31 10:37:54.379 2018.08.22 00:00:00 Super
2018.08.31 10:37:55.881 2018.08.22 00:00:00 Super
2018.08.31 10:37:56.631 2018.08.22 00:00:00 Super
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment