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