Reputation: 4771
I have just started to study C++, and right now I am working with pointers. I cannot understand why the following thing is happening.
So, say I have two classes A and B. A has an integer field (int valueA) and B has a pointer field (to A), A *a. Below I have shown both classes.
class A{
A::A(int value){
valueA = value;
}
void A::displayInfo (){
cout<<A<<endl;
}
}
class B{
B::B(){
a=0;
}
void B::printInfo (){
a -> displayInfo(); //Segmentation fault
}
void B::process(){
A new_A = A(5);
a = &new_A;
new_A.displayInfo(); //correct output
a -> displayInfo(); //correct output
}
}
Now when in my main class I do the following: create an instance of the B class and call the process() and print() functions. In the output I get: 5(which is correct), 5(which is correct) and Segmentation fault. Can anyone please help me understand why this is happening? According to my current understanding of pointers, I am doing the correct thing?
int main(void) {
B b_object();
b_object.process();
b_object.print();
}
Just to make this clear, I have an A.h and B.h file where I declare "int valueA;" and "A *a;" respectively. And I know this can be done much easier without pointers, but I am trying to learn how pointers work here :D
Upvotes: 0
Views: 175
Reputation: 110758
A new_A = A(5);
a = &new_A;
Here you create new_A
which is local to process
and assign its address to a
. When the process
function ends, new_A
goes out of scope and is destroyed. Now a
points at an invalid object.
The real solution here is to not use pointers like this, but if you really have to, to have something last beyond the end of the function you need to dynamically allocate it. Do this with a = new A(5);
. You need to make sure that you delete a;
at some later point in the program, otherwise the dynamically allocated memory will be leaked.
Upvotes: 3
Reputation: 46435
The variable a
is local to your methods - declare it at the class level
Upvotes: 0
Reputation: 4647
a is assigned to a local variable in process() therefore not valid in printInfo()
Upvotes: 0