简体   繁体   中英

C++ call virtual method in child class

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.

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) {
  ...
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM