Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Okay, I'm writing a game that has a vector of a pairent class (enemy) that s going to be filled with children classes (goomba, koopa, boss1) and I need to make it so when I call update it calls the childclasses respective update. I have managed to create a example of my problem.

#include <stdio.h>
class A{
    public:
        virtual void print(){printf("Hello from A");}
};

class B : public A{
    public:
        void print(){printf("Hello from B");}
};


int main(){
    A ab = B();
    ab.print();
    while(true){}
}

Output wanted: "Hello from B" Output got: "Hello from A"

How do I get it to call B's print function?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
434 views
Welcome To Ask or Share your Answers For Others

1 Answer

Polymorphism only works on pointers and references. If you assign a B to an A, it becomes an A and you lose all B-specific information, including method overrides. This is called "slicing"; the B parts are "sliced" off the object when it is assigned to an object of a parent class.

On the other hand, if you assign a B* to an A*, it looks like an A*, but is still really pointing to a B, and so the B-specific information remains, and B's virtual overrides will be used.

Try:

int main(){
    A* ab = new B();
    ab->print();
    delete ab;
    while(true){}
}

The same also applies to assigning a B to an A& (reference-to-A), e.g.

int main(){
    B b;
    A& ab = b;
    ab.print();
    while(true){}
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...