Pointers To Objects

Just a quick, simple question...why doesn't this work. I can't work it out.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

using namespace std;

class stuff
{
public:
    char derp;
};
stuff metal;
stuff *epic;

int main()
{
    metal.derp = 'd';
    *epic = metal;
    cout << *epic.derp;
    cin.get();
    return 0;
}
Epic is unassigned.

It's simply a dangling pointer pointing somewhere in memory and likely not where you want it to point. You need to "move" it to point to the address metal is stored:

epic = &metal;

pre-pending '*' to epic accesses what epic is pointing to. Leaving off the asterisk will give you or allow you to set the memory location.
Last edited on
---/main.cpp||In function ‘int main()’:|
---/main.cpp|17|error: request for member ‘derp’ in ‘epic’, which is of non-class type ‘stuff*’|
||=== Build finished: 1 errors, 0 warnings (0 minutes, 0 seconds) ===|


Is the error I got after replacing *epic = metal with epic = &metal
---/C++ Applications/Tester/main.cpp||In function ‘int main()’:|
---/main.cpp|17|error: request for member ‘derp’ in ‘epic’, which is of non-class type ‘stuff*’|
||=== Build finished: 1 errors, 0 warnings (0 minutes, 0 seconds) ===|

That is the error I got after replacing *epic = metal with epic = &metal
ok, let me set this up locally and see where I'm going wrong. It's looking like a cast issue.

My bad, I forgot you also need to dereference the pointer in the output statement:

epic->derp;

It's a pointer to higher level data structure, so '->' tells the compiler to get the char at "offset" such and such from the address epic is pointing to.
Last edited on
It works! Thanks a bunch, though I had to get rid of the dereference operator for it to work.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

using namespace std;

class stuff
{
public:
    char derp;
};
stuff metal;
stuff *epic;

int main()
{
    metal.derp = 'd';
    epic = &metal;
    cout << epic->derp;
    cin.get();
    return 0;
}
Topic archived. No new replies allowed.