Sign in to follow this  

vector and objects (c++)

This topic is 3623 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

So I am trying to write an object that contains a member vector of objects. As far as I can see I wrote it correctly but my compiler is still giving me this error among others. Any help would be apreciated.
class Item//---------------------------------<<Class Item>>----------------------------------------------------------
{
public:
	Item(string name, int slot, int stam, int inte, int armor, int agi, int str, int spirit);//constructor
	static int s_TotalItems;//numer of total items
	void DisplayStats();//display func for all stats
	friend void equip(Item& rTempItem);

//private:
	string m_Name;
	int m_ItemID;//unique id not use for nothing now
	int m_Slot;// it can't onyl be equipt into that slot in the heros inventory
	int m_Stam;
	int m_Inte;
	int m_Armor;
	int m_Agi;
	int m_Strgn;
	int m_Spirit;
};

int Item::s_TotalItems = 0;//define the static member data
Item::Item(string name, int slot, int stam, int inte, int armor, int agi, int str, int spirit):
	m_Name(name),
	m_Slot(slot),
	m_Stam(stam),
	m_Inte(inte),
	m_Armor(armor),
	m_Agi(agi),
	m_Strgn(str),
	m_Spirit(spirit)
{
	m_ItemID = s_TotalItems + 1;
	++s_TotalItems;
}

void Item::DisplayStats()
{
	cout << "Name: " << m_Name << endl;
	cout << "Item ID: " << m_ItemID << endl;
	cout << "Slot: " << slots(m_Slot) << endl;//return string
	if(m_Stam != 0)// only displays the value if the stat is not "0"
		cout << "Stamina: " << m_Stam << endl;
	if(m_Inte != 0)
		cout << "Intelect: " << m_Inte << endl;
	if(m_Armor != 0)
		cout << "Armor: " << m_Armor << endl;
	if(m_Agi != 0)
		cout << "Agility: " << m_Agi << endl;
	if(m_Strgn != 0)
		cout << "Strenght: " << m_Strgn << endl;
	if(m_Spirit != 0)
		cout << "Spirit: " << m_Spirit << endl;
}
//---------------------------------<<Class Item/>>----------------------------------------------------------
//---------------------------------<<Class Pool>>----------------------------------------------------------
class IPool
{
public:
	IPool(string kind);
	void Add(Item& rItem);//adds item object to vector
	void Display();//display list if item objects
	vector<Item> m_Items;// hold item objects
	string m_PoolKind;// type of pool
}

IPool::IPool(string kind)//constructor
{
	m_PoolKind = kind;
}

void IPool::Add(Item& rItem)//adds item to vector m_Items
{
	m_Items.push_back(rItem);
}

void IPool::Display()
{
	for(vector<Item>::const_iterator iter = m_Items.begin(); //creates an iter for vector<Item>
		iter != m_Items.end();
		++iter)
		cout << *iter << endl;// display each item
}

This is the compile error I get: 1>c:\users\raffaga\documents\visual studio 2008\projects\dressthehero\dressthehero\test.cpp(89) : error C2533: 'IPool::{ctor}' : constructors not allowed a return type 1>c:\users\raffaga\documents\visual studio 2008\projects\dressthehero\dressthehero\test.cpp(173) : error C2264: 'IPool::IPool' : error in function definition or declaration; function not called

Share this post


Link to post
Share on other sites
OMG I see it now!
But there is a problem with my iterator in Pool::Display()

error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'std::_Vector_const_iterator<_Ty,_Alloc>' (or there is no acceptable conversion)

and when I call this in my main:

IPool Items(string);
Items.Add(Item(string, int, int, int, int, int, int, int));

I get this error:

error C2064: term does not evaluate to a function taking 8 arguments

but class Item does take 8 arguments!

Share this post


Link to post
Share on other sites
Quote:
Original post by raffagapro
But there is a problem with my iterator in Pool::Display()

error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'std::_Vector_const_iterator<_Ty,_Alloc>' (or there is no acceptable conversion)


You haven't defined (overloaded) the operator (<<) of your Item class, so the compiler doesn't know what to do with it. I suspect you want it to call Item::DisplayStats(), so you'll be getting something along the lines of:


class Item
{
/* ... */
friend std::ostream & operator<<( std::ostream & os, const Item & val );
};

std::ostream & operator<<( std::ostream & os, const Item & val )
{
val.DisplayStats( /*os*/ ); // see below
return os;
}




However, you might want to refactor your Item::DisplayStats() method and supply it an output stream as an argument, instead of hard-coding the use of cout. Also, that method needs to have the const-modifier, or the compiler will complain when it sees the example code above (or you could just pass the object as a non-constant reference).

Quote:
Original post by raffagapro
and when I call this in my main:

IPool Items(string);
Items.Add(Item(string, int, int, int, int, int, int, int));

I get this error:

error C2064: term does not evaluate to a function taking 8 arguments

but class Item does take 8 arguments!


A temporary object cannot be passed as a non-constant reference to a function/method. Your void IPool::Add( Item & rItem ) should be void IPool::Add( const Item & rItem ). Alternatively, you could first define and initialize an object and then supply it:


Item item( "some item", 1, 2, 3, 4, 5, 6, 7 );
Items.Add( item );




EDIT: fixed small error in top code block
EDITEDIT: error on my account, see answer below...


[Edited by - Todo on January 7, 2008 7:44:23 PM]

Share this post


Link to post
Share on other sites
Quote:
Original post by Todo

A temporary object cannot be passed as a non-constant reference to a function/method. Your void IPool::Add( Item & rItem ) should be void IPool::Add( const Item & rItem ). Alternatively, you could first define and initialize an object and then supply it:


I tried what you said; I defined the object and then added to my IPool, and added const to my function. It worked, but i have 3 questions;

1. Is IPool just saving references of Item Object into its vector m_Items or is it actually making a copy of the object?

2. Why is it that a temporary object cannot be passed as a non-constant to a function? I thought my function IPool::Add created and item and then add it to its vector, how is it a temporary object?

3. Even when adding "const" to void IPool::Add(Item& rItem), I still get the same compile erro. It only works when I first define the ITEM object and then add it to IPool. Why is that? I've seen other people using a function like void IPool::Add(Item& rItem) to define and add object at the same time.

Thanks for your help. This is helping me a lot in my learning experience =D

Share this post


Link to post
Share on other sites
Quote:
Original post by raffagapro
1. Is IPool just saving references of Item Object into its vector m_Items or is it actually making a copy of the object?


A copy.

Quote:
Original post by raffagapro
2. Why is it that a temporary object cannot be passed as a non-constant to a function?


I was wrong making that statement. This isn't a case of an implicit temporary object. My best bet is you're using a non-conformant compiler that's having difficulties parsing code. It compiles fine here. Apologies none-the-less ;-). Just fyi, here's an example of an implicit temporary object that can't get passed by (non-const) reference:


void foo( std::string & woei )
{
woei = "bar";
}

void test()
{
std::string someString( "foo!" );

foo( someString ); // OK
foo( "foo?" ); // C2664: 'foo' : cannot convert parameter 1 from 'const char [5]' to 'std::string &'
}




The reason for this behavior could be viewed as the temporary object having no physical location in memory (although in truth, that's not really true), so you can't really pass it around by reference.

Quote:
Original post by raffagapro
3. Even when adding "const" to void IPool::Add(Item& rItem), I still get the same compile erro. It only works when I first define the ITEM object and then add it to IPool. Why is that? I've seen other people using a function like void IPool::Add(Item& rItem) to define and add object at the same time.

Thanks for your help. This is helping me a lot in my learning experience =D


See 2) and no problem :-). Cheers!

Share this post


Link to post
Share on other sites
Quote:
Original post by Todo
Quote:
Original post by raffagapro
2. Why is it that a temporary object cannot be passed as a non-constant to a function?


I was wrong making that statement. This isn't a case of an implicit temporary object. My best bet is you're using a non-conformant compiler that's having difficulties parsing code. It compiles fine here. Apologies none-the-less ;-).

Actually, you were right making that statement, and yours is the non-conformant compiler. The standard specifies that non-const references cannot be bound to temporaries. More here.

Share this post


Link to post
Share on other sites
Quote:
Original post by Todo
Quote:
Original post by raffagapro
1. Is IPool just saving references of Item Object into its vector m_Items or is it actually making a copy of the object?


A copy.



So if I wanted to store 100 objects in the vector inside IPool, I would ende up using 200 chunks of memory; 100 when defining the Item objects and 100 when calling the IPool::Add functing?

I am sorry if I keep drilling in things like this, I am just trying to understand the concept, so I can apply them correctly in future programs. You answers were right since the first post, but all this is giving me a deeper understanding of all these concepts.

Share this post


Link to post
Share on other sites
Quote:
Original post by Sneftel
Quote:
Original post by Todo
Quote:
Original post by raffagapro
2. Why is it that a temporary object cannot be passed as a non-constant to a function?


I was wrong making that statement. This isn't a case of an implicit temporary object. My best bet is you're using a non-conformant compiler that's having difficulties parsing code. It compiles fine here. Apologies none-the-less ;-).

Actually, you were right making that statement, and yours is the non-conformant compiler. The standard specifies that non-const references cannot be bound to temporaries. More here.


And here.

Share this post


Link to post
Share on other sites
So I wrote a new function for my class IPool...


void IPool::Searcher(string item)
{
vector<Item>::const_iterator iter;
for(iter = m_Items.begin(); iter != m_Items.end(); ++iter)//pulls the string name of each object
{
if(((*iter).GetName()) == item)// comparest it to the item
(*iter).DisplayStats();//displays the object in the vetor from which name is = to item
}
}



and now I get this error, any ideas?

error C2662: 'Item::DisplayStats' : cannot convert 'this' pointer from 'const Item' to 'Item &'
1> Conversion loses qualifiers

Share this post


Link to post
Share on other sites
Quote:
Original post by Driv3MeFar
Quote:
Original post by Sneftel
Actually, you were right making that statement, and yours is the non-conformant compiler. The standard specifies that non-const references cannot be bound to temporaries. More here.


And here.


Good to know that non-conformant compiler seems to be Microsoft's very own that came with VS2008 then ;-). Anyhow, thanks for clearing that up (both of you).

Share this post


Link to post
Share on other sites
Quote:
Original post by raffagapro
Quote:
Original post by Todo
Quote:
Original post by raffagapro
1. Is IPool just saving references of Item Object into its vector m_Items or is it actually making a copy of the object?


A copy.



So if I wanted to store 100 objects in the vector inside IPool, I would ende up using 200 chunks of memory; 100 when defining the Item objects and 100 when calling the IPool::Add functing?


Yes, but the first 100 would then be destructed almost immediately, and the memory made available again.

Actually, there might be more chunks of memory being allocated freed, depending on the initial size of the vector and how you add the elements. But at the end of the process, you won't be wasting memory: temporary copies get cleaned up automatically.

EDIT: Also, it looks like you really need to read the section on const correctness, too.

Share this post


Link to post
Share on other sites
Thanks that article helped me understand a bit more about "const correctness". I feel like I almost got it. I might be running to a similar problem here:


void bagStore(string item, vector<string>& rModBag);
int main()
{
const int MAX_BAG_SLOTS = 11; //needed to work on setting a set # of slots
vector<string> heroBag(MAX_BAG_SLOTS, "Empty");

bagStore("Helm of Wrath", heroBag);
}
void bagStore(string item, vector<string>& rModBag)
{
vector<string>::iterator bagIter;//iterator to acess the vector
string empty = "Empty";
bagIter = find(rModBag.begin(), rModBag.end(),empty);//find first empty slot and stores item
//cout << *bagIter;<---use to see the changes while running the program
*bagIter = item;//changes the object in the vector for the string item
//cout << *bagIter;<---use to see the changes while running the program
//system("pause");<---use to see the changes while running the program
}




I don't get a compile error, but the changes to heroBag alias "pModBag" in bagStore function aren't being pass back to the vector heroBag, any ideas why?

Share this post


Link to post
Share on other sites

This topic is 3623 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this