So while writing a game of mine, I ran into a problem that has mixed me up on how I thought pointers worked. I was just a little over 125% sure the following worked. So let me first explain a bit on how I see pointers working in one way, to see if someone can catch a problem if any.
Lets say you had two pointers:
Code:
type* a = NULL;
type* b = NULL;
You had one pointed to heap memory:
and then you had 'b' point to what 'a' points to, and then afterwards you were to set the fields through 'b':
Code:
a = b;
b->field_one ( 0 );
b->field_two ( 0 );
Now, if I check the values of those two fields through 'a', they come out exactly as I expected them too.
Now the large code block labled
'MAIN TEST CODE' seems more or less the same to me. Except 'b' would point to what 'a' points to by the means of a member function of a class. Such as:
Code:
class some_class
{
//...
public:
type* a ( void ) const;
//...
};
//...
b = some_class->a ();
If I were to set the type that 'a' points to through 'b', 'a' seems unaffected.
My question is why? I was convinced before this and still am to some degree that I have done this before, but I can't find the code that proves this(I've lost some code over the past month so maybe it was there). Am I doing something wrong that I am oblivious to? Or am I wrong on me thinking that I have done this before?
The following code I mentioned a couple times earlier roughly demonstrates in a condensed way how exactly my game operates at a certain point, where the problem lies.
'MAIN TEST CODE'
Code:
#include <iostream>
struct data
{
int a, b;
};
class one
{
private:
data* var_data;
public:
data* get_data ( void ) const { return var_data; }
void del_data ( void ) { delete var_data; }
one () { var_data = NULL; }
};
void set_data ( data* i )
{
i = new data;
i->a = 3;
i->b = 4;
// Here it is shown that the data has been set.
std::cout << "set_data:: i->a == " << i->a << " : i->b == " << i->b << "\n";
}
int main ()
{
one a;
set_data ( a.get_data () );
data* b = a.get_data ();
// Yet the pointer to the same (or at least it should be the same) data
// shows it not being set.
std::cout << b->a << " " << b->b << "\n";
std::cout << a->a << " " << a->b << "\n";
a.del_data ();
return 0;
}
Thanks in advance.