Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static member modification in const member function in C++

Tags:

c++

I am working on linked-list but can't modify the value of current pointer in const function "void Print() const"

In the function Print I want to do "current= head" & then increment like "current=current->link" but can't do so, bcz it is showing that

"error C3490: 'current' cannot be modified because it is being accessed through a const object e:\Cpp\projects\data structure ass-1\data structure ass-1\source.cpp 83 1 Data Structure Ass-1 "

#include<iostream>

struct node
{
    int data;
    node *link;
};    

class List
{
    node *head,*current,*last;
public:
    List();
//  List(const List&);
//  ~List();

void print() const;

};

using namespace std;

int main()
{
    List List1;
}

void List::print() const
{
     current=head;   //here is my error
     current=current->link;
}

List::List():current(head)
{

}
like image 388
Sohail Haider Avatar asked Dec 25 '22 21:12

Sohail Haider


2 Answers

If a member function of a class is declared as const:

void print() const;

it means, that this function cannot modify the data members of its class. In your case variables:

node *head,*current,*last;

cannot be modified in the body of print(). Thus you cannot change addresses these pointers point to. A way round this problem is to define a local variable temp in your print() function. Such a variable can be modified and do the same job as current was supposed to do:

void List::print() const
{
    node *temp;     
    temp=head;   
    temp=temp->link;
}
like image 136
cpp Avatar answered Jan 17 '23 16:01

cpp


When you declare a const member function the this pointer becomes const inside the const function when that is called for an object.

Meaning the const member function prevents any direct or in-direct modification of the data members of class.

Direct implies like the one you're doing in your program(modifying the data members directly in the const member function which is violating the purpose of it). It is ok to do any operations involving data members unless you're not modifying them. Also, you can call other const member functions inside a const member function.

And Indirect means you can't even call other non-const member functions of the class because they might modify the data members.

Usually const member functions are used when you just want to get/ read the values. Hence, in your case you shouldn't use a const member function.

Also, you can call non-const and const member functions for a non-const object.

like image 29
Uchia Itachi Avatar answered Jan 17 '23 17:01

Uchia Itachi