-3

I do not understand why line 21 is ok but line 25 is error?

The error message:

invalid conversion from 'const int*' to 'int*' [-fpermissive]

Push is function in class that decleared like this:

template< typename Type >  
class Stack { 
    void Push(const Type& value) {
       SNode* type = new SNode();
       if (this->head != nullptr) { 
           this->head->up = temp;
       }
       temp->value = value;
       temp->up = nullptr;
       temp->down = head;
       temp->head = temp;
       num_of_elements++;
   }
};

int main() {
    Stack<int*>* stk = new Stack<int*>();
    int a = 5;
    int* x = &a;
    stk->Push(x); //this line is fine
    const int b = 5;
    const int* y = &b;
    stk->Push(y); //this line is an error
    delete stk;
    return 0;
}

It's look like function Push get parameter from type of "const int * &" , and in line 25 , i exactly sends a const pointer "const int *". so what is the problem?

Joe
  • 8,868
  • 8
  • 37
  • 59
BestMath
  • 1
  • 1
  • It would help if you had a better title and you included the error message in your question. You might also want to make the function in question not private. – Retired Ninja May 05 '17 at 00:27
  • Your error is thinking that `Push()` is waiting for a `const int * &`; it's waiting for a `int * const &`; a total different type (hope my answer can explain better). – max66 May 05 '17 at 00:31

1 Answers1

1

The Push() in line 21

int a = 5;
int * x = &a;
stk->Push(x);

where Push() wait for a const Type & value (with Type equal to int *, if I understand correctly), works because you're sending a int * to a method that is wainting for a compatible type, a const Type & that is int * const &.

Remember that const is applied on the left, on the right when there isn't nothing on the left, so const Type & is Type const & that is int * const &. So is a reference to a constant pointer to a not-constant integer.

When you write (Push() in line 25)

const int b = 5;
const int * y = &b;
stk->Push(y);

you're sending a const int *, that is a int const * (not-constant pointer to a constant integer), to a method that is waiting for a int * const & (a reference to a constant pointer to a not-constant integer).

The two types are incompatibles, so the error.

You can try with

int b = 5;
int * const y = &b;
stk->Push(y);

This should work.

max66
  • 65,235
  • 10
  • 71
  • 111