In below code snippet , I am trying to add the intefeger and float values in Array template but was surprised to see below
output for float value as 5.1 was expected there but getting 0 . Can anybody let me know what can be wrong here.
output

value=5
value=15
size=10
value=0
value=5.2
size=3
value=5
value=15
size=10
value=0 // It should have print the 5.1 here instead of 0
value=5.2
size=3

code snippet:

    #include <iostream>
        using namespace std;
        template <typename T , int buffer>
        class Array
        {
        T array [buffer];
        public:
        void setval(T x,int index )
        {
        array[index]=x;

        }

        T getval(int index)
        {
        if(index < buffer)
        {
        return array[index];
        }

        return -1;
        }
        int size ()
        {
         return buffer;   
        }

        };
        int main()
        {
        Array<int,10> s;
        s.setval(5,0);
        cout<<"value="<<s.getval(0)<<endl;
        s.setval(15,1);
        cout<<"value="<<s.getval(1)<<endl;
        cout<<"size="<<s.size()<<endl;
        Array<float,3> s1;
        s.setval(5.1,0);
        cout<<"value="<<s1.getval(0)<<endl;
        s1.setval(5.2,1);
        cout<<"value="<<s1.getval(1)<<endl;
        cout<<"size="<<s1.size()<<endl;
        return 1;
        }

Tiny typo --

Line 38 : s.setval(5.1,0);
Should have beens1.setval(5.1,0);

There are ways round this kind of error (scoping the two test etc) but in reality better naming is more important. I hate any name that can be confused with another name by one character missing/changed etc. However I guess you wrote this as a test code and didn't worry about it -- we all have done that!

Thanks. yes , In real implementation will take care the same .

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.