Pointers...! Argh!

Hi people,
pointers are devil! Why this code compile and make a console crash?

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;

class C{
    public:
    string name;

    C(){
        name = "pippo";
    }
};
class B{
    public:
    C * p_C;

    B(){
        C c;
        p_C = &c;
    }
};
class A{
    public:
    B * p_B;

    A(){
        B b;
        p_B = &b;
    }
};

int main(){
    A a;
    cout << a.p_B->p_C->name;

    return 0;
}
b is a local variable inside the A() constructor. When the constructor ends b will no longer exist so p_B end up being a pointer to an object that no longer exist, and using such an object is not "safe" and could lead to program crash.
Ok, thanks, i understand. How can i have a pointer to object outside the class where is the pointer? Or, how can i create an object inside a class and assign a pointer to that object?
Why do you want to use a pointer in the first place? Can't you just make A store a B object directly?
I think his examples are for brushing up on his pointer knowledge, they are rather crude.


How can i have a pointer to object outside the class where is the pointer?

Could you clarify?

how can i create an object inside a class and assign a pointer to that object?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Ect
{
public:
        Ect() {}
};

class Obj
{
private:
        Ect ect;
public:
        Obj(Ect *e) { ect = *e; }
};

int main()
{
Ect *ect1;
Obj obj1(ect1);
}


Is that what you mean?
Topic archived. No new replies allowed.