c++ - error: invalid initialization of reference of type 'int&' from expression of type 'const int' -
this unrelated question code in this question, regarding following template function.
template <class t> class object : public container { public: t& object; object(const t& obj) : object(obj) {} };  this code calls constructor:
template <class t> void array::add_element(const t& element) { vec.push_back(new object<t>(element)); }  this code compiles fine, add line in main calls it:
array array; int = 3; array.add_element(i);  i compiler warning: error: invalid initialization of reference of type 'int&' expression of type 'const int'.
what about? passed int in. shouldn't automatically turned const int& me? why compiler complaining?
obj const reference. object non-const reference.
you can't initialize non-const reference const reference, because doing defeat purpose of having const reference in first place.
if want instance of object able modify int that's passed constructor, constructor should take non-const reference. if don't, data member should const reference.
in case, storing trouble if use new allocate objects have references data members. it's your problem ensure delete object before i goes out of scope (or anyway, ensure object doesn't use member object after i goes out of scope.
Comments
Post a Comment