Your operator=
function doesn't return anything, when it's suppose to be returning a reference to an object of type test
. So change this:
test& operator=(const T & new_value)
{
value = new_value;
}
To this:
test& operator=(const T & new_value)
{
value = new_value;
//dereference the "this" pointer to get a lvalue reference to
//the current object
return *this;
}
Note that by accessing the implicit this
pointer of a class (that is the pointer that is pointing to the instance class itself in memory that a method is being called on), and dereferencing it, you are accessing a lvalue reference of the class instance. So if you are returning an lvalue reference from your class method, that reference can then be passed to other functions that take references as arguments, and/or other methods can be called on that returned class instance. This allows the operator=
to be used in "chains" of functions and method calls, where after the operator=
method is called, another method is called on the resulting modified object instance. For instance, you could do something like:
test<int> a;
a.value = 5;
int b = (a = 6) + 5; //outputs the value 11
If you had created a print()
method for your test
object, you could also do something like the following:
test<int> a;
a.value = 7;
(a = 8).print();
This code returns the test
class instance a
after the operator=
method, and then calls the print()
method on that instance, printing out the value 8
.