Search code examples
c++methodspolymorphismvirtual

Calling a subclassed virtual method from a base class method


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!


Solution

  • 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