Reputation: 367
template<class D>
class Animal{
public:
D a;
Animal(){
a=0;
}
};
template<class D>
Animal<D>& addAnimal(Animal<D>& ans, const Animal<D>& a, const Animal<D>& b){
ans.a = a.a + b.a;
return ans;
}
//an overloaded simpler method for the one above
template<class D>
Animal<D> addAnimal(const Animal<D>& a, const Animal<D>& b){
return addAnimal( Animal<D>(),a,b);
}
int main() {
Animal<int> a;
Animal<int> b;
Animal<int> c = addAnimal(a,b);
}
The following doesn't compile. Why not? I know I can fix this by making the ans
parameter pass by value OR changing the call to that method by doing:
template<class D>
Animal<D> addAnimal(const Animal<D>& a, const Animal<D>& b){
Animal<D> ans;
return addAnimal(ans,a,b);
}
I want a better understanding of pass by reference and how to call the default constructor of a stack object. Thanks!
Upvotes: 0
Views: 44
Reputation: 206607
The line
return addAnimal( Animal<D>(),a,b);
does not work because Animal<D>()
is a temporary object, which cannot be used in a function call that expects a non-const
lvalue reference.
More importantly, it is not clear to me why you need the overload
template<class D>
Animal<D>& addAnimal(Animal<D>& ans, const Animal<D>& a, const Animal<D>& b) { ... }
You can implement the simpler, two argument, function as:
template<class D>
Animal<D> addAnimal(const Animal<D>& a, const Animal<D>& b){
Animal<D> ans;
ans.a = a.a + b.b;
return ans;
}
and get rid of the other one altogether.
Upvotes: 2