This is an unrelated question about the code in this question, regarding the following template function.
template <class T>
class Object : public Container {
public:
T& object;
Object(const T& obj) : object(obj) {}
};
This is the code that calls the constructor:
template <class T>
void Array::add_element(const T& element)
{
vec.push_back(new Object<T>(element));
}
This code compiles fine, but as soon as I add a line in main that calls it:
Array array;
int i = 3;
array.add_element(i);
I get a compiler warning: error: invalid initialization of reference of type 'int&' from expression of type 'const int'.
What is that about? I passed an int in. Shouldn’t it automatically be turned into a const int& for me? Why is the compiler complaining?
objis a const reference.objectis a non-const reference.You can’t initialize a non-const reference from a const reference, because doing so would defeat the purpose of having a const reference in the first place.
If you want your instance of
Objectto be able to modify theintthat’s passed to its constructor, then the constructor should take a non-const reference. If you don’t, then the data member should be a const reference.In any case, you are storing up trouble for yourself if you use
newto allocate objects that have references as data members. It’s your problem to ensure that you delete theObjectbeforeigoes out of scope (or anyway, ensure that theObjectdoesn’t use its memberobjectafterigoes out of scope.