Jump to content
  • Advertisement
Sign in to follow this  
dcuk

pointer problem

This topic is 4751 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

hey i can't work out where to put the pointer in as wherever i put it at moment creates problems, so their must be an easier way. im trying to make the function able to return the name of a particular item without repeating big chunks of code, so thought the way im going is right way, but hey i'm new so all part of learning.
[source='cpp']
void Store::Sell(Player & player, int type) {
	//Weapon* mPoint;
	//Armour* mPoint;
	int select=0;
	string cat="Default";
	if(type == 1) { 
		cat = "Weapon";
		Weapon * mPoint = new Weapon;
		*mPoint = player.GetWeapon();
	}
	if(type == 2) { 
		cat = "Armour"; 
		Armour * mPoint = new Armour;
		*mPoint = player.getArmor();
	}
	else if(type == 3) { cat = "Item"; }
	//Weapon * mPoint=0;
	switch ( type ) {
		case 1: 
			//Weapon * mPoint = new Weapon;
			//*mPoint = player.GetWeapon();
			cout << cat << ": " << mPoint->mName << "\n";
			cout << mPoint->mName << ": value is " << mPoint->mValue << "\n";
			break;
	}
	cout << "1) Sell	2) Keep";
	cin>>select;
	if(select == 1) {
		player.gold((mPoint->mValue)*2);

	}
	if(select == 2) { return; }
}

Share this post


Link to post
Share on other sites
Advertisement
It seems you're looking for polymorphism. You'll need a base class 'Item' (or something along those lines) and inherit specific items such as class Weapon : public Item, class Armor : public Item, etc.
If you add generic properties (such as price, name, etc.) that are shared by all items to the Item base class, you can indeed access these by an Item*:

Item *item = new Weapon("Twig");
cout << item->Name(); // will print Twig
item = new Armor("Pink Dress +2");
cout << item->Name(); // will now print Pink Dress +2


Tom

Share this post


Link to post
Share on other sites
I think the easiest part for this would be parent class Item of Weapon and Armor

which has virtual functions getName() and getValue()

You would only need a pointer

Item* item

which will get eitger the return of getWeapon or getArmor

and than you can call the Functions getName and getValue on this pointer an you get what you want.
For this getWeapon and getArmour should best also return pointers, or you keep your code and you will have the following line:

item = &weapon; or item = &armor;

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!