The problem of overriding a virtual function

Well, I am writing a game that has a paired class (enemy) vector that will be filled with child classes (goomba, koopa, boss1), and I need to do this when I invoke the update, it invokes the corresponding update for the child classes. I managed to create an 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){}
}

Requires output: "Hello from B" The result is received: "Hello from A"

How do I get it to call print function B?

+3
source share
3 answers

. B A, A, B, . ""; B "" , .

, B* A*, A*, - B, B - , B .

Try:

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

B A& (reference-to-A),

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

, .

+3

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

struct Base_Class
{
  virtual void update(void)
  {
    cout << "Updating Base_Class.\n";
  }
};

struct Goomba : public Base_Class
{
  void update(void)
  {
     // Invoke the parent method first.
     Base_Class::update();

     // Perform Descendant operations
     cout << "Updating Goomba\n";
  }
};

Here is the implementation:

#include <iostream>
using std::cout;

void Update_Player(Base_Class& b)
{
  b.update();
  return;
}

int main(void)
{
   Goomba g;
   g.update();

   Goomba g2;
   std::vector<Base_Class *> container;
   container.push_back(&g);
   container.push_back(&g2);

   std::vector<Goomba>::iterator iter;
   for (iter =  container.begin();
        iter != container.end();
        ++iter)
   {
       Update_Player(*(*iter));
   }

   return 0;
}
0
source

Source: https://habr.com/ru/post/1747596/


All Articles