what happened to the heap?

closed account (SECMoG1T)
I have a simple snippet here, what makes me wonder is how it compiles with no error or warnings because i can easily manipulate constant parameters on my
= operator and my incr function, do you think this is a bug with my IDE?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>

using namespace std;

struct dat
{
  int *x;
  dat():x(new int(1)){};
  dat(int n): x(new int(n)){}
  dat(const dat& a):x(new int(*a.x)){}

  dat& operator =(const dat&);

  void incr(const dat& rhs)const {*x=(*rhs.x*=5);}
  ~dat(){delete x; x=nullptr;}
};

dat& dat::operator=(const dat& p)
{
    if(this!=&p)
        *x=++*p.x;

     return *this;
}

int main()
{

int i=0;
dat a,b(12);

 while(i<10)
  {
    a.incr(b);
    cout<<"value on a :"<<*a.x<<"  value on b  :"<<*b.x<<endl; ++i;
  }
}


Thanks in advance.
Last edited on
You cannot. Only data in your class is x pointer and you never change it outside your constructor and assigment operator.

value this pointer points to, is not part of the class and const qualifier for *this has no relation to it.
closed account (SECMoG1T)
Thanks @Miinnipaa for that BTW does that suppose to mean that my class nonstatic members and members allocating their resources on the heap exist as two different entities? meaning that we are free to alter any values held on the heap.

What if am using those members to store really senstive values on the heap, how would i prevent such illegal manipulations if possible coz you said that const qualifier for *this has no relation to it.
Last edited on
how would i prevent such illegal manipulations
It is your class. You are writing it. Just do not do that.
To be somewhat safer, you can use accessors and use them even inside your class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
struct dat 
{
    dat():x(new int(1)) {};
    dat(int n): x(new int(n)) {}
    dat(const dat& a):x(new int(a.get_x())) {}

    dat& operator =(const dat&);

    void incr(const dat& rhs)const
    {  get_x()=(rhs.get_x()*=5); } //Illegal now
    ~dat() { delete x; }
private:
    int* const  x; //You do not need to change ponter value anyway.
          int& get_x()       {return *x;}
    const int& get_x() const {return *x;}
};

dat& dat::operator=(const dat& p)
{
    if(this!=&p)
        get_x()=++p.get_x(); //Illegal now
     return *this;
}

closed account (SECMoG1T)
Thank you very much, that makes sense now haha, i just couldn't figure it out.
Topic archived. No new replies allowed.