-1

I have the following code:

#include<cstdio>
#include<iostream>
#include<cmath>
using namespace std;
template <class T> class Stack
{
private:
    T a[1001];
    int i=0,j;
public:
    void pop(void)
    {
        a[i-1]=0.0;
        a[i-1]='\0';
    }
    void push(T &x)
    {
        a[i++]=x;
    }
    void push(const char &x)
    {
        a[i++]=x;
    }
    void top(void)
    {
        cout<<a[i-1];
    }
};
int main()
{
    Stack<char>s1;
    s1.push('a');
    s1.push('b');
    s1.top();
    s1.pop();
    cout<<"\n";

    Stack<int>s2;
    s2.push(10);
    s2.push(20);
    s2.top();
    s2.pop();
    cout<<"\n";

    Stack<double>s3;
    s3.push(5.50);
    s3.push(7.50);
    s3.top();
    s3.pop();
    cout<<"\n";

    return 0;
}

output:

b
20
7

why it's showing 7 for double instead of 7.5 ?
when i explicitly specialize for double and don't use reference operator it works well.

void push(double x)
{
    a[i++]=x;
}

this gives correct output for double. but, when i do this it gives error.

void push(T x)
{
    a[i++]=x;
}
void push(const char &x)
{
    a[i++]=x;
}

how to fix this ?
how to show correct output for double ?

MD. Khairul Basar
  • 4,976
  • 14
  • 41
  • 59

2 Answers2

3

When you use

s3.push(7.50);

it resolves to the overload

void push(const char &x)
{
    a[i++]=x;
}

since 7.5 cannot be converted to double&, which will be needed to use:

void push(T &x)
{
    a[i++]=x;
}

As a result, you get the truncated value of 7 in the stack.

If you want the call to resolve tovoid push(T &x), create a variable and use the variable in the call.

double x = 7.5;
s3.push(x);
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • @KhairulBasar When the argument type is `const&`, the input value is truncated in a temporary memory location and the temporary memory location is passed to the function. – R Sahu Oct 17 '14 at 03:41
  • 1
    Another possible fix is for `push` to take `x` by value or by const reference – M.M Oct 17 '14 at 03:43
  • thank you. but if i simply use void push(char &x) it works well for all...is it okay or it will create bug ? – MD. Khairul Basar Oct 17 '14 at 03:43
1

I'd like to add to R Sahu's answer. In C++11, a new type of reference called the r-value reference has been introduced. R-value references are used to refer to unnamed variables, which in this case is what 7.5 is.

What R Sahu meant by "7.5 cannot be converted to double&" is that an l-value reference, which is your double&, cannot be bound to an r-value, which is your 7.5.

L-value references T& can only be bound to l-values. R-value references T&& can only be bound to r-values. Read-only l-value references const T& however, can be bound to l-value or r-value, read-only or not. Therefore, function overload resolution will resolve to push(const char& x) because it takes in a read-only l-value reference.

Thank you for reading.

Nard
  • 1,006
  • 7
  • 8