views:

283

answers:

2

hi guys, i have the following classes:

class A {
protected:
     A *inner;
public:
    ....
    virtual void doSomething() = 0;
    ....
}

class B: public A {
   ...
   void doSomething() {
       if(inner != NULL)
           inner->doSomething();
   }
   ...
}

When I use inner->doSomething() I get a segmentation fault. What should I do in order to call inner->doSomething() in the B class?

thanks in advance.

+9  A: 

Without an explicit initialization of the member inner, it's possible for it to be both not NULL and point to invalid memory. Can you show us the code that explicitly initalizes inner?

An appropriate constructor for A would be the following

protected:
A() : inner(NULL) {
  ...
}
JaredPar
Alternative to JaredPar's suggestion, in the constructor, specify that inner = NULL. Insert breakpoint in the subclass's doSomething() and observe the value of inner?
Calyth
was not initializing it, since i expected is would be NULL and the if statement false. i did not know that it would be possible for an object to be both not NULL and point to invalid memory. i just did inner = NULL at B's construtor and solved the problem.thank you very much.
marcos
BEWARE: for all standard types (pointers, int, float, etc... also called built-in types) the variable is not initialized when built (there is no 'Default Constructors'). Since 'inner' is an attribute of A, it is the responsability of A's constructor to initialize it, otherwise you will have the problem with every child class...
Matthieu M.
Ok Matthieu, gonna put the inner initialization at A's constructor, thanks!
marcos
+4  A: 

though if you assign the A* to be the same as the B initialised this pointer you'll get a stack overflow ... Any reason you need the inner? Can't you just call A::DoSomething()?

Goz