Advertisement

C++ Question

Started by February 15, 2001 10:52 AM
11 comments, last by frank2000 23 years, 11 months ago
Somewhat longwinded, but here''s the basic idea

  //CCharacter Typesstatic int CHAR_TYPE = 0;static int SOLD_TYPE = 1;static int MONS_TYPE = 2;//BASE Classclass CCharacter{public:	int m_nType;	CCharacter(int nType) : m_nType(nType){}};//Soldier child classclass CSoldier : public CCharacter{public:	CSoldier() : CCharacter(SOLD_TYPE){}	void Attack(){		printf("FREEZE!  I AM A SOLDIER!  I K33L J00 NOW!\n");	}};//Monster child classclass CMonster : public CCharacter{public:	CMonster() : CCharacter(MONS_TYPE){}	void Growl(){		printf("RAR! I AM A MONSTER! PREPARE TO DIE!\n");	}};//Growl if pChar is a Monsterbool Growl(CCharacter *pChar){	if(pChar->m_nType == MONS_TYPE){		CMonster *pMons = (CMonster*)pChar;		pMons->Growl();		return true;	}	return false;}//Attack if pChar is a Soldierbool Attack(CCharacter *pChar){	if(pChar->m_nType == SOLD_TYPE){		CSoldier *pSold = (CSoldier *)pChar;		pSold->Attack();		return true;	}	return false;}int main(int argc, char* argv[]){	CMonster m;	CSoldier s;	Attack(&m);	Attack(&s);	Growl(&m);	Growl(&s);	return 0;}  

Thanks JonStelly. Your idea can address the problem, but for my program, this would result in hundreds or even thousands of comparisons in every frame. Anyway, thanks for your help.

Thanks you all. I think I would move all the public attributes of Soldier and Monster back to Character, and use virtual functions. This may be the easiest way to corrert my program.
Advertisement
Ok, I think I understand what you mean (I think ) BTW - you can access base class information from a derived class, but not the other way. You''ll want to use virtual functions to override functions:

class cBaseChar
{
public:
virtual void Attack() { cout << "ATTACK!"; }
};

class cHero : public cBaseChar
{
private:
long MySpecialData;
};

class cMonster : public cBaseChar
{
public:
void Attack() { cout << "GRRR!"; }
};

main()
{
cHero Hero;
cMonster Monster;

Hero.Attack();
Monster.Attack();
}


Jim Adams
Author "Programming Role-Playing Games with DirectX"
jimadams@att.net

This topic is closed to new replies.

Advertisement