Created
August 31, 2018 13:51
-
-
Save barenko/b2c0bff36d80c036f9e140e9d56724fe to your computer and use it in GitHub Desktop.
Generic pointer to access subclass methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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