Problem overridding virtual function

By : William
Source: Stackoverflow.com
Question!

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?

By : William


Answers

You need to call the parent's update method before any processing by the descendant classes:

struct Base_Class
{
  virtual void update(void)
  {
    cout 


Your virtual keyword is correctly placed, you need to use pointers or references though.



This video can help you solving your question :)
By: admin