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;
}
std::vector
and dont mess around with callingnew
anddelete
in places where they dont belongnullptr
is fine, this is why you do not get any further problems in this concrete case; deleting a dangling pointer, however, is fatal; droptab = nullptr;
from your destructor and your program is very likely to crash! On the other hand, if you do deletion correctly (in this case: just let the object run out of scope), you can drop this line anyway, as the object won't be there any more and it does not matter what the then unused space in memory is occupied with...