I have a class Outer with a nested class Inner. Inner has a method 'print' which tries to access a data member of class Outer. The code compiles fine but I get a segmentation fault error when I try to run the programme.
#include <iostream>
class Outer{
public:
Outer();
~Outer();
class Inner{
public:
Inner(Outer *parent){}
void print(){std::cout<< parent-> data <<std::endl;}
private:
Outer *parent;
};
Inner *obj;
private:
int data;
};
Outer::Outer(): data(99), obj(new Inner(this)){}
Outer::~Outer(){delete obj;}
int main(){
Outer outer;
outer.obj->print();
return 0;
}
I'm not sure what is the issue as I have already passed the 'this' pointer to the inner object.
The code is compiled with g++4.8.2 using the c++11 flag.
You must turn on compiler warnings and pay attention to them. In this case, the compiler is able to pinpoint the exact error in:
(The exact warning message may differ, but all major compilers are able to detect this if you don't prevent them from doing so by using some low default warning level.)
As you leave the
parentmember variable in an uninitialised status, the following line invokes undefined behaviour because you try to read from the variable:You must initialise the member variable:
That's not the only problem, though. There's also this:
You can fix it by simply changing the order as follows: