C++ call virtual method in child class
Asked Answered
I

2

6

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.

Interpret answered 30/9, 2009 at 15:14 Comment(3)
If you get a segfault when using inner, it's probably because it does not point to a valid object. How do you initialize inner in B?Metalworking
Every A contains an A*? Really? Why?Monoatomic
Ok, they're looking at each other. I just wanted to check.Monoatomic
Z
9

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) {
  ...
}
Zarger answered 30/9, 2009 at 15:17 Comment(5)
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?Sanguinaria
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.Interpret
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...Plante
Ok Matthieu, gonna put the inner initialization at A's constructor, thanks!Interpret
Can be shortened to A() : inner() { ... } albeit the more explicit form is more readable.Quaff
A
4

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()?

Aeolic answered 30/9, 2009 at 15:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.