Please read all of this, the information I\'ve included is hopefully enough to s
ID: 3743474 • Letter: P
Question
Please read all of this, the information I've included is hopefully enough to solve this problem. I need this issue solved as fast as possible. This is the important part, the compiler is giving me the error: "in call to 'T List<T>::at(int) [with T=Book*]'" for the first picture. The first picture shows two at() functions, the first has to return a const and the second one has to return a reference. I'm not sure if I did both of those right but yeah that's what they have to return. From the second picture the compiler is giving me the error: "passing 'const List<Book*>' as 'this' argument discards qualifers." Only when the List<Book*> is passed as const do I get this error so please I need some help ASAP.
Thanks, Ill be sure to upvote.
Explanation / Answer
When you are working on an object and calling some function you have to make sure the function does not change any thing in the object (because of the const). To assure that C++ provides a concept called constant function. When you know that your function is accessing some constant data and it is not changing the data but just accessing it, just the case described here, you have to declare the functions constant as below,
Suppose the function you are declaring is
returntype Funcition(arg1,arg2,...);
then to make it const function the declarition will be,
returntype Function(arg1,arg2, ...) const;
Following this the functions you defined will be defined as below,
template <class T>
const T List<T>::at(unsigned int index) const {
if(index > _size -1 || index < 0) {
throw std::out_of_range("oor");
}
else{
return array[index];
}
}
template <class T>
T& List<T>::at(int index) const {
if (index > _size-1 || index <0){
throw std::out_of_range("oor");
}
else {
return array[index];
}
}
Hope it solves your problem.
Happy Chegging!
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.