Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 458
marcosbeirigo Avatar asked Sep 30 '09 15:09

marcosbeirigo


People also ask

Can you call a virtual method?

The derived classes inject their own implementation and definition of the virtual method. This means that in your application, you are able to call a method on a base class and cause its derived class's method to be executed.

How do you call a virtual method from base class?

When you want to call a specific base class's version of a virtual function, just qualify it with the name of the class you are after, as I did in Example 8-16: p->Base::foo(); This will call the version of foo defined for Base , and not the one defined for whatever subclass of Base p points to.

Can a child class call base class methods?

A child class can access the data members of its specific base class, i.e., variables and methods.

Why is virtual method called virtual?

'virtual function' means a member function where the specific implementation will depend on the type of the object it is called upon, at run-time. The compiler and run-time support of the language contrive to make this happen. The keyword 'virtual' in C++ was taken from Simula, which had impressed Bjarne Stroustrup.


2 Answers

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) {
  ...
}
like image 91
JaredPar Avatar answered Sep 27 '22 22:09

JaredPar


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

like image 23
Goz Avatar answered Sep 27 '22 21:09

Goz