fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <memory>
  4. using namespace std;
  5.  
  6. class IA
  7. {
  8. public:
  9. virtual ~IA() {}
  10. void A() { cout << "A" << endl; }
  11. };
  12. class IB
  13. {
  14. public:
  15. virtual ~IB() {}
  16. void B() { cout << "A" << endl; }
  17. };
  18. class IC
  19. {
  20. public:
  21. virtual ~IC() {}
  22. void C() { cout << "A" << endl; }
  23. };
  24.  
  25. class C : IA, IB, IC
  26. {
  27. public:
  28. };
  29.  
  30. void QueryInterface(int n, C* cthis, void** ptr)
  31. {
  32. switch (n)
  33. {
  34. case 1:
  35. *ptr = reinterpret_cast<IA*>(cthis);
  36. break;
  37. case 2:
  38. *ptr = reinterpret_cast<IB*>(cthis);
  39. break;
  40. case 3:
  41. *ptr = reinterpret_cast<IC*>(cthis);
  42. break;
  43. }
  44. }
  45.  
  46. void QueryInterface2(int n, C* cthis, void** ptr)
  47. {
  48. switch (n)
  49. {
  50. case 1:
  51. *ptr = (IA*)cthis;
  52. break;
  53. case 2:
  54. *ptr = (IB*)cthis;
  55. break;
  56. case 3:
  57. *ptr = (IC*)cthis;
  58. break;
  59. }
  60. }
  61. int main() {
  62. IA* ptr;
  63. cout<<"Cpp style cast."<<endl;
  64. C c;
  65. QueryInterface(1, &c, (void**)&ptr);
  66. cout << ptr << endl;
  67. QueryInterface(2, &c, (void**)&ptr);
  68. cout << ptr << endl;
  69. QueryInterface(3, &c, (void**)&ptr);
  70. cout << ptr << endl;
  71.  
  72. cout<<"C style cast."<<endl;
  73. QueryInterface2(1, &c, (void**)&ptr);
  74. cout << ptr << endl;
  75. QueryInterface2(2, &c, (void**)&ptr);
  76. cout << ptr << endl;
  77. QueryInterface2(3, &c, (void**)&ptr);
  78. cout << ptr << endl;
  79.  
  80. return 0;
  81. }
Success #stdin #stdout 0s 4400KB
stdin
Standard input is empty
stdout
Cpp style cast.
0x7ffc457df220
0x7ffc457df220
0x7ffc457df220
C style cast.
0x7ffc457df220
0x7ffc457df228
0x7ffc457df230