Your answer is technically correct but there is a subtlty that you've missed.
The parameter variable - otherStack - is declared as a constant and is thus treated like a constant for the duration of the function. What the compiler was complaining about was that you called the member function
push(const Type & on this object. This is not allowed.
If you wish to have constant objects but still be able to use their member functions (or at least some of them), you need to give a guarantee that you won't alter any data members inside that member function. You do this by affixing the keyword
const to the end of the function header. This must also be in the definition if you put it in a separate source file. If you've got the const keyword there, the compiler will enforce your guarantee and prevent you from altering data members in that function.
eg
Language: C++
class myClass{
public:
int getValue() const;
void setValue(int newValue);
private:
int value;
};
int myClass::getValue() const{ // must include the const here too
return value; // this is allowed because you';re not changing the value.
}
// data are allowed to be changed in the next function because it';s not marked as a constant function. If it were, a compiler error would be generated on the line that changes the data member.
void myClass::setValue(int newValue) {
value = newValue;
}
////////
Usage
///////
int someFunction(const myClass &obj){
obj.setValue(10); // not allowed because obj is declared as a constant in the parameter list
return obj.getValue(); // this is allowed because getValue() has been declared as a constant function and guarantees that the data won';t be changed
}
I hope this makes things clearer.