1

I tested the program using static allocation and the compiler gives me an error when I had changed the value .

But when I used dynamic allocation, the value changed .

class Test{

private:
    int *value;

public:

    Test( int v ){
        value = new int;
        *value = v;
    }

    int getValue() const{
        *value = 110;
        return *value;
    }

    ~Test(){
        delete value;
    }

};
int main(){
    Test t1(7);
    cout<<t1.getValue()<<endl;
}
Raafat
  • 49
  • 8
  • that's because you are actually changing the value of the address pointed by "value" not changing the "value" itself. – hungryspider Apr 10 '19 at 04:10

2 Answers2

1

In short, you are modifying the pointed-to value and const keyword only guarantees that the member variable, in this case a pointer to int, will not change. You would run into issues if you were attempting to re-assign the pointer to value = 110 because you would be modifying the member variable.

There's a bit deeper explanation of this here if you'd like to dive deeper into it: https://stackoverflow.com/a/6853421/882338

rreichel
  • 794
  • 3
  • 9
  • 25
1

It's because the pointer member variable becomes const in your case and not the memory it is pointing to. You won't be able to reassign the pointer in this const member function.

vinodsaluja
  • 573
  • 6
  • 15