I'm a bit newbie to CPP and I don't know why the setValue() const
works meanwhile it's a const.
Why the class allows modification from a const public
It seems really odd, there is no error on 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;
}
So the const only means that the declared function can not be renamed, nor can the parameters be changed.
User-defined types, including classes, structs, and arrays, cannot be const .
Not in standard C, since there are no classes or objects (as in "class instances, i.e. collections of data with associated functions"), there's nothing for the function to be const "against".
Const member functions in C++ Like member functions and member function arguments, the objects of a class can also be declared as const. an object declared as const cannot be modified and hence, can invoke only const member functions as these functions ensure not to modify the object.
It is because you do not modify it. When you do:
int* tab
tab contains only an address. Then in
void DArray::setValue(unsigned n, int value) const // HERE
{
tab[n] = value;
}
You do not modify this address, you modify some memory after it. Thus you do not modify your class.
If instead, you used
std::vector<int> tab
You would have an error in setValue because you would modify an element of your class.
First of all, don't call explicitely the destructor of your class, this will be called when the variable goes out of scope automatically.
darray.~DArray();
What you are promising with const
in the method is that the member variables will not be modified. The variable int* tab
is a pointer to an int. With your setValue function you are not changing the address of the pointer (which is promised not to be changed by the final const in the signature of your method) but the int value pointed by it. This is fine.
However, if you change the pointer address, for example with tab = nullptr
, you will see a compiler error like:
error: assignment of member 'DArray::tab' in read-only object
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With