Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- using namespace std;
- class Object
- {
- public:
- virtual void BeginPlay();
- void ObjectFunction()
- {
- cout << "ObjectFunction() called.\n\n";
- }
- };
- class Actor : public Object
- {
- public:
- virtual void BeginPlay() override;
- void ActorFunction()
- {
- cout << "ActorFunction() called.\n\n";
- }
- };
- class Pawn : public Actor
- {
- public:
- virtual void BeginPlay() override;
- void PawnFunction()
- {
- cout << "PawnFunction() called.\n\n";
- }
- };
- int main()
- {
- Object* ptr_to_object = new Object;
- Actor* ptr_to_actor = new Actor;
- Pawn* ptr_to_pawn = new Pawn;
- // Since Actor and Pawn are Objects, they can be included in
- // an array of type Object
- Object* ObjectArray[] = { ptr_to_object, ptr_to_actor, ptr_to_pawn };
- // Because of polymorphism, even though we are looping through an
- // array of Objects, we are calling the specific override BeginPlay() function
- // from the derived classes
- for (int i = 0; i < 3; i++)
- {
- //ObjectArray[i]->BeginPlay();
- Object* obj = ObjectArray[i];
- // 'dynamic_cast will return nullptr if it can't be cast
- // to the pointer type.
- // static_cast will go ahead and cast regardless, ignoring
- // any errors.
- Actor* act = dynamic_cast<Actor*>(obj);
- if (act)
- {
- act->ActorFunction();
- }
- Pawn* pwn = dynamic_cast<Pawn*>(obj);
- if (pwn)
- {
- pwn->PawnFunction();
- }
- }
- delete ptr_to_object;
- delete ptr_to_actor;
- delete ptr_to_pawn;
- system("pause");
- }
- void Object::BeginPlay()
- {
- cout << "Object BeginPlay() called \n\n";
- }
- void Actor::BeginPlay()
- {
- cout << "Actor BeginPlay() called \n\n";
- }
- void Pawn::BeginPlay()
- {
- cout << "Pawn BeginPlay() called \n\n";
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement