Advertisement
GregLeck

Untitled

Feb 18th, 2022
599
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.72 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4.  
  5. class Object
  6. {
  7. public:
  8.     virtual void BeginPlay();
  9.  
  10.     void ObjectFunction()
  11.     {
  12.         cout << "ObjectFunction() called.\n\n";
  13.     }
  14.  
  15. };
  16.  
  17. class Actor : public Object
  18. {
  19. public:
  20.     virtual void BeginPlay() override;
  21.  
  22.     void ActorFunction()
  23.     {
  24.         cout << "ActorFunction() called.\n\n";
  25.     }
  26. };
  27.  
  28. class Pawn : public Actor
  29. {
  30. public:
  31.     virtual void BeginPlay() override;
  32.  
  33.     void PawnFunction()
  34.     {
  35.         cout << "PawnFunction() called.\n\n";
  36.     }
  37. };
  38.  
  39. int main()
  40. {
  41.     Object* ptr_to_object = new Object;
  42.     Actor* ptr_to_actor = new Actor;
  43.     Pawn* ptr_to_pawn = new Pawn;
  44.  
  45.     // Since Actor and Pawn are Objects, they can be included in
  46.     // an array of type Object
  47.     Object* ObjectArray[] = { ptr_to_object, ptr_to_actor, ptr_to_pawn };
  48.  
  49.     // Because of polymorphism, even though we are looping through an
  50.     // array of Objects, we are calling the specific override BeginPlay() function
  51.     // from the derived classes
  52.     for (int i = 0; i < 3; i++)
  53.     {
  54.         //ObjectArray[i]->BeginPlay();
  55.  
  56.         Object* obj = ObjectArray[i];
  57.  
  58.         // 'dynamic_cast will return nullptr if it can't be cast
  59.         // to the pointer type.
  60.         // static_cast will go ahead and cast regardless, ignoring
  61.         // any errors.
  62.         Actor* act = dynamic_cast<Actor*>(obj);
  63.  
  64.         if (act)
  65.         {
  66.             act->ActorFunction();
  67.         }
  68.  
  69.         Pawn* pwn = dynamic_cast<Pawn*>(obj);
  70.  
  71.         if (pwn)
  72.         {
  73.             pwn->PawnFunction();
  74.         }
  75.     }
  76.  
  77.     delete ptr_to_object;
  78.     delete ptr_to_actor;
  79.     delete ptr_to_pawn;
  80.     system("pause");
  81. }
  82.  
  83. void Object::BeginPlay()
  84. {
  85.     cout << "Object BeginPlay() called \n\n";
  86. }
  87.  
  88. void Actor::BeginPlay()
  89. {
  90.     cout << "Actor BeginPlay() called \n\n";
  91. }
  92.  
  93. void Pawn::BeginPlay()
  94. {
  95.     cout << "Pawn BeginPlay() called \n\n";
  96. }
  97.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement