Why can I change the class using the const function in C ++ 11?

I'm a little new to CPP and I don't know why setValue() const works in the meanwhile as const.

Why does a class allow modification from const public

It seems really strange there is no error in g ++ -Wall or with MS Visual C ++

Here is my code:

main.cpp

 #include <iostream> #include <cassert> #include "DArray.h" int main(void) { DArray darray(1); darray.setValue(0, 42); assert(darray.getValue(0) == 42); darray.~DArray(); system("pause"); return 0; } 

DArray.h

 class DArray { private: int* tab; public: DArray(); DArray(unsigned int n); ~DArray(); int& getValue(unsigned int n) const; void setValue(unsigned int n, int value) const; }; 

DArray.cpp

 #include "DArray.h" DArray::DArray() { } DArray::DArray(unsigned int n) { tab = new int[n]; } DArray::~DArray() { delete[] tab; tab = nullptr; } int& DArray::getValue(unsigned n) const { return tab[n]; } void DArray::setValue(unsigned n, int value) const // HERE { tab[n] = value; } 
+7
c ++ c ++ 11
source share
3 answers

This is because you do not change it. When you do:

 int* tab 
Tab

contains only the address. Then in

 void DArray::setValue(unsigned n, int value) const // HERE { tab[n] = value; } 

You do not change this address, after it you change some memory. This way you do not change your class.

If you used instead

 std::vector<int> tab 

You will have an error in setValue, because you must change the element of your class.

+17
source share

First of all, do not explicitly call the destructor of your class, this will be called when the variable automatically goes out of scope.

DArray ~ DArray () ;.

What you promise with const in the method is that member variables will not be changed. The int* tab variable is a pointer to an int. Using the setValue function, you do not change the address of the pointer (which is not supposed to be changed by the final const in the signature of your method), but the int value specified by it. It is perfectly.

However, if you change the address of the pointer, for example, using tab = nullptr , you will see a compiler error, for example:

error: assigning member "DArray :: tab" in read-only object

+6
source share

Why can I change the class using the const function in C ++ 11?

You can change the mutable state of an object. It is also technically possible to change the non- const_cast state using const_cast , but it would be a bad idea to do this, because if the object itself is constant, then the behavior will be undefined.

This is not what you do in this code.

why setValue () const works while it is const.

Because it does not change the this member. It modifies the array pointed to by a pointer to non-constant. A member function constant or an object constant is not transferred to an indirectly pointed object.

+2
source share

All Articles