开发者

Calling a subclassed virtual method from a base class method

开发者 https://www.devze.com 2022-12-16 06:44 出处:网络
class A { public: virtual void doSomething(void) {} void doStuff(void) { doSomething(); } }; class B : public A { public:
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!


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.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消