samedi 19 avril 2014

c ++ - appel d'une méthode virtuelle sous-classé d'une méthode de classe de base - Stack Overflow


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!




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




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.




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



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!



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



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.



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


0 commentaires:

Enregistrer un commentaire