views:

100

answers:

3

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;    
}
+1  A: 

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%5Foperator%5Fin%5FC%2B%2B

San Jacinto
+4  A: 

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.

SebastianK
There is no compiler-generated assignment operator because a non-default constructor has been declared, not because there is a reference. A reference could by copied by compiler-generated code, but the other constructor disables compiler-generation of default constructor and assignment operator.
MP24
@MP24: Sorry, but you are wrong here. How should the compiler implement assignment for a reference? He can not, because the existing can not be changed.No default constructor is generated, if a non-default constructor is provided, perhaps you meant this? It has nothing to do with an compiler generated assignment operator.
SebastianK
Indeed. If you want to share the "reference" and want the class to be assignable, use a pointer member (if the class doesn't manage memory for the shared object, otherwise `std::tr1::shared_ptr`).
UncleBens
A: 

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

Space_C0wb0y