views:

157

answers:

3
class A
{
public:
    virtual void
        doSomething(void)
    {}

    void
        doStuff(void)
    {
        doSomething();
    }
};

class B : public A
{
public:
    void
        doSomething(void)
    {
        // do some stuff here
    }
};

B * b = new B;
b->doStuff();

It gives me Segmentation fault. What am I doing wrong? It should work well in my opinion!

A: 

You should not have the : after class A and public A...

KennyTM
My bad. But it wasn't the problem anyway.
Balon
+5  A: 

After I corrected the syntax errors and added a main() function, it compiled and executed for me with no problems. Try posting the REAL code that causes the problem, and rethink your code formatting.

anon
+1  A: 

As far as I can see, you're not doing any polymorphism in the code bellow the class definition.

b->doStuff() should call the method of B class. If you want to inside B call A-> doSomething you can use A:: doSomething

Andres
B hasn't got a doStuff member - so A::doStuff will be called.
anon
He's calling the non-polymorphic `doStuff`, whose implementation invokes the polymorphic `doSomething`.
ChrisW
I am calling `doStuff()` which is declared in `B` class and called from `A` class.
Balon
@Balon, not in the code you posted.
anon
Sorry, I misspelled the name, I intended to say `doSomething`
Andres
Now I understand what ChrisW ment. Yes, I'm calling the non-polymorphic `doStuff`, whose implementation invokes the polymorphic `doSomething`, but it occurs with Segmentation fault in my code.
Balon
@Balon So post the code that causes the fault!
anon
Okay, thanks. You helped me to solve this out.
Balon