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.
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.
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.
A child class can access the data members of its specific base class, i.e., variables and methods.
'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.
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()?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With