Noga
Noga

Reputation: 145

Compiler error when adding an object to a vector

Why do I get the following compiler error when adding an object to a vector, which its data member is referencing another object?

The compiler error:

Error 1 error C2582: 'operator =' function is unavailable in 'Product' c:\program files\microsoft visual studio 8\vc\include\xutility 2726

In the program I collect all data before I create a new Product object,

then, creating the object and passing all data to the constructor:

the problem is in the push_back(p) line,

vector<Product> productsArr;
vector<string> categoriesArr;

class Product

{

private:
  string m_code;    
  string m_name;    
  string& m_category_ref;     
  string m_description;    
  double m_price;    
  Product();    
public:
  Product(const string& code,const string& name,string& refToCategory,   
  const string& description, const double& price):m_category_ref(refToCategory)    
  {    
    m_code = code;
    m_name = name;
    m_description = description;
    m_price = price;
  }

}

void addProduct()
{    
  string code,name,description;    
  double price;    
  int categoryIndex;    
  getProductData(code,name,price,categoryIndex,description);    
  Product p(code,name,categoriesArr[categoryIndex],description,price);    
  productsArr.push_back(p);    
}

the line from the xutility:

// TEMPLATE FUNCTION fill
template<class _FwdIt, class _Ty> inline
void __CLRCALL_OR_CDECL _Fill(_FwdIt _First, _FwdIt _Last, const _Ty& _Val)
{ // copy _Val through [_First, _Last)
 _DEBUG_RANGE(_First, _Last);
  for (; _First != _Last; ++_First)
   *_First = _Val;    
} 

Upvotes: 2

Views: 683

Answers (3)

Bj&#246;rn Pollex
Bj&#246;rn Pollex

Reputation: 76778

Objects that you add to STL-Containers have to be Assignable

Upvotes: 0

SebastianK
SebastianK

Reputation: 3707

The object must be assignable (Needs operator=) to be used with an STL container.

There is no compiler generated operator=, because you have a reference (m_category_ref) as a member.

Upvotes: 5

user124493
user124493

Reputation:

You must write an operator= function for your class, just as the compiler tells you.

you should read this link. It's a pretty good summary of copying in C++

http://en.wikipedia.org/wiki/Assignment_operator_in_C%2B%2B

Upvotes: 1

Related Questions