Home > Net >  const function modifying data in Doubly Linked List
const function modifying data in Doubly Linked List

Time:10-18

I have created a doubly linked list. in the list, there is a function that is const, and is not supposed to modify the object. but it is modifyind I dont know why.

#include<iostream>
using namespace std;
class Node {
public:
    int data;
    Node* prev;
    Node* next;
    Node(int val) :data(val), next(NULL), prev(NULL) {}
};
class List {
    Node* head;
    Node* tail;
public:
    List() :head(NULL), tail(NULL) {}
    void addToTail(int val) {
        Node* temp = new Node(val);
        if (head == NULL) {
            head = temp;
            tail = temp;
        }
        else {
            tail = head;
            while (tail->next != NULL) {
                tail = tail->next;
            }
            tail->next = temp;
            temp->prev = tail;
            tail = temp;

        }
    }

    int search(int val) const
    {
        if (head->data == val)
            head->data = 12;
        return head->data;
    }
};
int main()
{
    List l;
    l.addToTail(1);
    l.addToTail(2);
    l.addToTail(3);
    l.addToTail(4);
    l.addToTail(5);

    int c = l.search(1);
    //c = 102;
    cout << c;
}

Now I have tried to use const before the return type, but obviously it doesnt matter. it does not affect the result; in the search(int val) function, I am sending a value to check if 'head->data' is equal to the 'val', it should not modify the 'head->data = 12' because the function is const. but it is doing this.

CodePudding user response:

The const qualifier for the member function only tells the compiler that you won't modify this object.

And you don't do that: You modify head->data which is another object.

It would be a different issue if you tried to reassign the variables head or tail.

  • Related