Weird output with template class and generic types. What is happening? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Weird output with template class and generic types. What is happening?

https://code.sololearn.com/c64SUEDmLFHj This program yields some weird output but don´t know why. I expect it to give me the greater of two or four numbers but obj1, obj2, obj3 return 7 digit numbers. Someone has an answer or had anything similar like in this case? Output expected: Output returned: 66 66 48 4264281 48 8917632 48 4264123 48 48 531.4 531.4 template <class T> class Pair { private: T first, second, third, forth; public: // Pair takes 2 or 4 parameters of any type Pair(T a, T b, T c, T d) :first(a), second(b), third(c), forth(d) {}; Pair(T a, T b) :first(a), second(b) {}; auto bigger(); }; template <class T> auto Pair<T>::bigger() { T returnValue1 = (first > second ? first : second); T returnValue2 = (third > forth ? third : forth); T returnValue = (returnValue1 < returnValue2 ? returnValue2 : returnValue1); return returnValue; }; int main() { Pair<double>obj(54, 33.2, 44, 66); cout << obj.bigger() << endl; Pair<long long>obj1(48, 33.2); cout << obj1.bigger() << endl; Pair<long long>obj2(48, 33.2); cout << obj2.bigger() << endl; Pair<long>obj3(48, 33.2); cout << obj3.bigger() << endl; Pair<long>obj4(48, 33.2); cout << obj4.bigger() << endl; Pair<float>obj5(531.4, 33.2, 44, 66.67); cout << obj5.bigger() << endl; }; Output: 66 4264281 8917632 4264123 48 531.4

12th Nov 2018, 7:54 PM
Jonap TSCHÄGE
Jonap TSCHÄGE - avatar
1 Answer
+ 1
You should initialize third and fourth even with the constructor taking only two values or those attributes will have junk values like that
12th Nov 2018, 7:59 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar