Page 1 of 1

[SOLVED] Polymorphism Help

Posted: Tue Apr 13, 2010 9:31 pm
by GroundUpEngine
I swear I've done this before and it worked, wtf.. or maybe i'm just tired :(

test.cpp

Code: Select all

#include <iostream>
using namespace std;

class Entity {
  public:
    Entity();
    ~Entity();
};
class Actor : public Entity {
  public:
    Actor() : Entity() {}
    ~Actor() {}
};
class Player : public Actor {
  public:
    Player() : Actor() {}
    ~Player() {}

    int testVar;
    void Shoot() {};
};

int main()
{
    Actor* test = new Player();
    test->testVar = 0;
    test->Shoot();
    
    cin.get();
    delete test;
    return 0;
}
Error: (16) 'class Actor' has no member named 'testVar'
Error: (17) 'class Actor' has no member named 'Shoot'


Purpose: I wanna use it in this function, so I can return a generic Actor or a Player

Code: Select all

ActorManager TestManager;
Actor* TestActor;
TestActor = TestManager.GetPlayer("TestName");
---

Actor* ActorManager::GetPlayer(const string &name)
{
	// Check if the Player is not Already Loaded
	map<string, Actor*>::iterator iter = Actors.find(name);
	if((Actors.size() < MAX_ACTOR_COUNT) && (iter == Actors.end()))
	{
		Actor* act = new Player();
		act->name = name;
		Actors[name] = act;

		cout << name << " is new player\n";
	}
	return Actors[name];
}

Re: Polymorphism Help

Posted: Tue Apr 13, 2010 10:45 pm
by XianForce
well, testVar and Shoot() aren't in the Actor class. They are in the player class.

Because you have a pointer to an Actor, you can only use anything an Actor has.

So to solve, either chain up the variable/function or make virtual functions.

Re: Polymorphism Help

Posted: Wed Apr 14, 2010 8:58 am
by GroundUpEngine
XianForce wrote:well, testVar and Shoot() aren't in the Actor class. They are in the player class.

Because you have a pointer to an Actor, you can only use anything an Actor has.

So to solve, either chain up the variable/function or make virtual functions.
Thanks, ye I was looking for an alternative but maybe I'll just use some virtual functions in the base class instead.

Re: Polymorphism Help

Posted: Wed Apr 14, 2010 10:18 am
by RyanPridgeon
You could put it in a Player pointer temporarily to call the function

Code: Select all

int main()
{
    Actor* test = new Player();
    test->testVar = 0;
    Player* temp = test;
    temp->Shoot();
    
    cin.get();
    delete test;
    return 0;
}

Re: Polymorphism Help

Posted: Wed Apr 14, 2010 10:23 am
by Falco Girgis
You could also just as easily cast it. XD

Re: Polymorphism Help

Posted: Wed Apr 14, 2010 10:39 am
by RyanPridgeon
GyroVorbis wrote:You could also just as easily cast it. XD
Oh yeah, d'oh

Re: Polymorphism Help

Posted: Wed Apr 14, 2010 10:46 am
by GroundUpEngine
RyanPridgeon wrote:
GyroVorbis wrote:You could also just as easily cast it. XD
Oh yeah, d'oh
My thoughts exactly, Thanks guys! :)